Android mkdirs() sdcard do not work - android

I want to make dir in Sdcard, and i do follow:
I added: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in manifest.
I get root_path by: public static final String ROOT_PATH = Environment.getExternalStorageDirectory().toString() + "/Hello_World/"; and it returns
/storage/emulated/0/Hello_World (getting when debug).
Next, I run this code:
File file = new File(Constants.ROOT_PATH);
int i = 0;
while (!file.isDirectory() && !file.mkdirs()) {
file.mkdirs();
Log.e("mkdirs", "" + i++);
}
I also tried both mkdirs() and mkdir() but it's showing endless loop in logcat (Log.e("mkdirs", "" + i++);). Sometimes it work, but sometimes not.
Thanks for you helping!
Update: I tried my code for some devices: Nexus4, nexus7, Vega Iron, Genymotion, LG G Pro, then just Vega Iron work as expected. ??!!?!?

Try like this it will create a folder in the sd card
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello_world");
myDir.mkdirs();
If you want to check that file exists or not use this code
File file = new File (myDir, file_name);
if (file.exists ())
// file exist
else
// file not exist
For reference look at this answer Android saving file to external storage

The error is cause by && in while (!file.isDirectory() && !file.mkdirs()) it should be while (!file.isDirectory() || !file.mkdirs()). You should also check if the media is mounted.
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
if (DEBUG) {Log.d(TAG, "createSoundDir: media mounted");} //$NON-NLS-1$
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage != null)
{
String externalStoragePath = externalStorage.getAbsolutePath();
File soundPathDir = new File(externalStoragePath + File.separator + "Hello_World"); //$NON-NLS-1$
if (soundPathDir.isDirectory() || soundPathDir.mkdirs())
{
String soundPath = soundPathDir.getAbsolutePath() + File.separator;
if (DEBUG) {Log.d(TAG, "soundPath = " + soundPath);} //$NON-NLS-1$
}
}
}
Cut and paste from one of my project.

Thank all you guys, finally i found out the problem. The problem is in the while() loop, I replace by
if
(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
&& !file.isDirectory()) {
file.mkdirs(); }

Use Environment.getExternalStorageDirectory().getAbsolutePath() as below...
public static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Hello_World/";
And Check that SDCard is mounted before creating directory as below....
File file = new File(Constants.ROOT_PATH);
int i = 0;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if(!file.exists()) {
file.mkdir();
}
}

Related

how to create a folder in android External Storage Directory?

I cannot create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String Path = Environment.getExternalStorageDirectory().getPath().toString()+ "/Shidhin/ShidhiImages";
System.out.println("Path : " +Path );
File FPath = new File(Path);
if (!FPath.exists()) {
if (!FPath.mkdir()) {
System.out.println("***Problem creating Image folder " +Path );
}
}
Do it like this :
String folder_main = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
If you wanna create another folder into that :
File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1");
if (!f1.exists()) {
f1.mkdirs();
}
The difference between mkdir and mkdirs is that mkdir does not create nonexistent parent directory, while mkdirs does, so if Shidhin does not exist, mkdir will fail. Also, mkdir and mkdirs returns true only if the directory was created. If the directory already exists they return false
getexternalstoragedirectory() is already deprecated. I got the solution it might be helpful for you. (it's a June 2021 solution)
Corresponding To incliding Api 30, Android 11 :
Now, use this commonDocumentDirPath for saving files.
Step: 1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step: 2
public static File commonDocumentDirPath(String FolderName){
File dir = null ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+FolderName );
} else {
dir = new File(Environment.getExternalStorageDirectory() + "/"+FolderName);
}
return dir ;
}
The use of Environment.getExternalStorageDirectory() now is deprecated since API level 29, the option is using:
Context.getExternalFilesDir().
Example:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
file.delete();
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
return file.exists();
}
I can create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String folder_main = "Images";
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
if (!outerFolder.exists()) {
inerDire.createNewFile();
}
outerFolder.mkdirs(); // This will create a Folder
inerDire.createNewFile(); // This will create File (For E.g .jpg
file)
we can Create Folder or Directory on External storage as :
String myfolder=Environment.getExternalStorageDirectory()+"/"+fname;
File f=new File(myfolder);
if(!f.exists())
if(!f.mkdir()){
Toast.makeText(this, myfolder+" can't be created.", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, myfolder+" can be created.", Toast.LENGTH_SHORT).show();
}
and if we want to create Directory or folder on Internal Memory then we will do :
File folder = getFilesDir();
File f= new File(folder, "doc_download");
f.mkdir();
But make Sure you have given Write External Storage Permission.
And Remember that if you have no external drive then it choose by default to internal parent directory.
I'm Sure it will work .....enjoy code
If you are trying to create a folder inside your app directory in your storage.
Step 1 : Add Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 2 : Add the following
private String createFolder(Context context, String folderName) {
//getting app directory
final File externalFileDir = context.getExternalFilesDir(null);
//creating new folder instance
File createdDir = new File(externalFileDir.getAbsoluteFile(),folderName);
if(!createdDir.exists()){
//making new directory if it doesn't exist already
createdDir.mkdir();
}
return finalDir.getAbsolutePath() + "/" + System.currentTimeMillis() + ".txt";
}
This is raw but should be enough to get you going
// create folder external located in Data/comexampl your app file
File folder = getExternalFilesDir("yourfolder");
//create folder Internal
File file = new File(Environment.getExternalStorageDirectory().getPath( ) + "/RICKYH");
if (!file.exists()) {
file.mkdirs();
Toast.makeText(MainActivity.this, "Make Dir", Toast.LENGTH_SHORT).show();
}
Try adding
FPath.mkdirs();
(See http://developer.android.com/reference/java/io/File.html)
and then just save the file as needed to that path, Android OS will create all the directories needed.
You don't need to do the exists checks, just set that flag and save.
(Also see : How to create directory automatically on SD card
I found some another thing too :
I had the same problem recently, and i tryed abow solutions and they did not work...
i did this to solve my problem :
I added this permission to my project manifests file :
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
(plus READ and WRITE permissions) and my app just worked correctly.
try {
String filename = "SampleFile.txt";
String filepath = "MyFileStorage";
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText(myData);
response.setText("SampleFile.txt data retrieved from External Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}

How to create folder in sdcard in android

I want to make folders in my sdcard and I have used the code below:
public class Screen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
operateOnFirstUsage();
}
private void operateOnFirstUsage() {
String state = Environment.getExternalStorageState();
Log.d("Media State", state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
File appDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/");
Log.d("appDirectroyExist", appDirectory.exists() + "");
if (!appDirectory.exists())
Log.d("appDir created: ", appDirectory.mkdir() + "");
File dbDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Database/");
Log.d("dbDirectroyExist", dbDirectory.exists() + "");
if (!dbDirectory.exists())
Log.d("dbDir created: ", dbDirectory.mkdirs() + "");
File themesDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Themes/");
Log.d("themesDirectroyExist", themesDirectory.exists() + "");
if (!themesDirectory.exists())
Log.d("themesDir created: ", themesDirectory.mkdirs() + "");
}
}
}
Also, I have set the sdcard write permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I've run the application several times and every time I get the LogCat output:
01-09 21:38:13.701: D/Media State(15363): mounted
01-09 21:38:13.701: D/appDirectroyExist(15363): false
01-09 21:38:13.701: D/appDir created:(15363): false
01-09 21:38:13.701: D/dbDirectroyExist(15363): false
01-09 21:38:13.701: D/dbDir created:(15363): false
01-09 21:38:13.701: D/themesDirectroyExist(15363): false
01-09 21:38:13.701: D/themesDir created:(15363): false
I have read similar question, but nothing useful to get. What should I do to get the code running? What is my problem?
Edited
Try this:
File mydir = new File(Environment.getExternalStorageDirectory() + "/mydir/");
if(!mydir.exists())
mydir.mkdirs();
else
Log.d("error", "dir. already exists");
And recheck permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is how I created folder MyDir in the Pictures folder od sdcard:
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyDir");
mediaStorageDir.mkdirs();
Try this way:
File file=new File(Environment.getExternalStorageDirectory() + File.separator +"MyApp/");
file.mkdirs();
Try this code:) , its simple.
String fileName = "CallHistory.pdf";
// create a File object for the parent directory
File PDF_Directory = new File("/sdcard/MOBstate/");
// have the object build the directory structure, if needed.
PDF_Directory.mkdirs();
// create a File object for the output file
File outputFile = new File(PDF_Directory, fileName);
// now attach the OutputStream to the file object, instead of a ring representation
FileOutputStream fos = new FileOutputStream(outputFile);
I don't know why the application acted that way, but finally I overcame this problem by removing and resetting the sdcard write permission in the Android manifest file. Thanks all of you for your kind help and apologize for taking your time.

How to check for the existence of a file?

String extra=imagepath.get(i).toString();
String extra2=imageid.get(i).toString();
String path = "/mnt/sdcard/Android/data/com.example.webdata/files/Download/" + extra2 + ".jpg";
File f = new File(path);
if(f.exists())
{
//Toast.makeText(getApplicationContext(), "File already exists....",
// Toast.LENGTH_SHORT).show();
}
else
{
downloadfile();
}
I am using the above code to check if a file exists or not. I have checked it with one file and it works fine, but when I use it in my application where there are multiple (100-200) images it always starts downloading files whether they exist or not. Is there a better method than this?
First check how many images on folder:-
File extStore = Environment.getExternalStorageDirectory();
File[] imageDirs = extStore.listFiles(filterForImageFolders);
after above you run the loop and check u r condition:-
for(int i=0;i<list.length;i++)
{
// ur condition
}

file.mkdirs() not working

i want to write to a file in the sdcard of my phone.i used the below code to do this.
private CSVWriter _writer;
private File _directory;
public String _fileTestResult;
private String PATH_FILE_EXPORT = "/applications/foru/unittestframework/";
public ExportData(){
_writer=null;
_directory = new File(Environment.getExternalStorageDirectory () +PATH_FILE_EXPORT);
if(!_directory.exists())
_directory.mkdirs();
}
public void exportResult(String testcaseNum,String testcase,String status){
try {
if(_directory.exists()){
//do something
}
but mkdirs() is not working.so i could not excecute following code in the if condition.please help me.
note:i have given the permission in manifest file.
EDIT:
i am using this file write option for storing the result of automation testing using robotium.i have created a normal project and tried to create directory in sdcard.but the same code when i am using in this testproject it is not working.why like that?dont unit testing framework support this?
have you add the correct permission in your manifest ?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit : ok, i just read your note for permission.
If it's help you this is my sdcard cache code :
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
String evtDir = "";
if(evt > 0){
evtDir = File.separator + evt;
}
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "Android"
+ File.separator
+ "data"
+ File.separator
+ Application.getApplicationPackageName()
+ File.separator + "cache"
+ evtDir);
}else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
Try below code
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
imagefolder = new File(root,
mycontext.getString(R.string.app_name));
imagefolder.mkdirs();
}
} catch (Exception e) {
Log.e("DEBUG", "Could not write file " + e.getMessage());
}
Try with:
if(!_directory.exists())
_directory.mkdir();
Also check this - Creating a directory in /sdcard fails

Check if directory exist on android's sdcard

How do I check if a directory exist on the sdcard in android?
Regular Java file IO:
File f = new File(Environment.getExternalStorageDirectory() + "/somedir");
if(f.isDirectory()) {
....
Might also want to check f.exists(), because if it exists, and isDirectory() returns false, you'll have a problem. There's also isReadable()...
Check here for more methods you might find useful.
File dir = new File(Environment.getExternalStorageDirectory() + "/mydirectory");
if(dir.exists() && dir.isDirectory()) {
// do something here
}
The following code also works for java files:
// Create file upload directory if it doesn't exist
if (!sdcarddir.exists())
sdcarddir.mkdir();
General use this function for checking is a Dir exists:
public boolean dir_exists(String dir_path)
{
boolean ret = false;
File dir = new File(dir_path);
if(dir.exists() && dir.isDirectory())
ret = true;
return ret;
}
Use the Function like:
String dir_path = Environment.getExternalStorageDirectory() + "//mydirectory//";
if (!dir_exists(dir_path)){
File directory = new File(dir_path);
directory.mkdirs();
}
if (dir_exists(dir_path)){
// 'Dir exists'
}else{
// Display Errormessage 'Dir could not creat!!'
}
I've made my mistake about checking file/ directory. Indeed, you just need to call isFile() or isDirectory(). Here is the docs
You don't need to call exists() if you ever call isFile() or isDirectory().
Yup tried a lot, beneath code helps me :)
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "ur directory name");
if (!folder.exists()) {
Log.e("Not Found Dir", "Not Found Dir ");
} else {
Log.e("Found Dir", "Found Dir " );
Toast.makeText(getApplicationContext(),"Directory is already exist" ,Toast.LENGTH_SHORT).show();
}

Categories

Resources