Skip to content Skip to sidebar Skip to footer

File.mkdir() And Mkdirs() Are Creating File Instead Of Directory

I use the following code: final File newFile = new File('/mnt/sdcard/test/'); newFile.mkdir(); // if I use mkdirs() result is the same And it creates an empty file! Why?

Solution 1:

You wouldn't use mkdirs() unless you wanted each of those folders in the structure to be created. Try not adding the extra slash on the end of your string and see if that works.

For example

finalFilenewFile=newFile("/mnt/sdcard/test");
newFile.mkdir();

Solution 2:

When I need to ensure that all dirs for a file exist, but I have only filepath - i do

   new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();

Solution 3:

First of all you shouldn't use a file path with "/mnt/sdcard/test", this may cause some problems with some android phones. Use instead:

publicfinalstaticStringAPP_PATH_SD_CARD="/Test";

StringfullPath= Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD;

It creates an empty file since you added the dash.

Now that you have your path use the following code:

try {
    Filedir=newFile(fullPath);
    if (!dir.exists()) {
         dir.mkdirs();
    }
}
catch(Exception e){
    Log.w("creating file error", e.toString());
}

Solution 4:

Try to use

String rootPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/test/";
            File file=newFile(rootPath);
if(!file.exists()){
file.mkdirs();
}

Post a Comment for "File.mkdir() And Mkdirs() Are Creating File Instead Of Directory"