File.mkdir() and mkdirs() are creating file instead of directory
Asked Answered
P

4

11

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?

Procrustes answered 19/12, 2012 at 13:44 Comment(6)
are you sure, it is an empty file?Claudetta
----rwxr-x system sdcard_rw 9873Procrustes
cat /mnt/sdcard/test —> /mnt/sdcard/test: invalid lengthProcrustes
You should, at a minimum, always check the return values of functions that can return errors.Eterne
are you sure /mnt/sdcard exists?Gluey
also are you sure that a file and a dir with the same name can exits?Gluey
B
20

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

final File newFile = new File("/mnt/sdcard/test");
newFile.mkdir();
Bosh answered 19/12, 2012 at 13:47 Comment(1)
There isn't a "/mnt/sdcard" that points to the real sdcard on all Android devices (KitKat). I tried also the two slashes trick at the end with "/storage/external_SD/Android/data/<package_name>/files/dummy//" and it now creates a directory files which is visible on Windows, but dummy is still a file. With ES3 both are directories. Good enough for me :))Crabbing
D
7

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();
Delighted answered 25/9, 2014 at 6:47 Comment(0)
C
2

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:

public final static String APP_PATH_SD_CARD = "/Test";

String fullPath = 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 {
    File dir = new File(fullPath);
    if (!dir.exists()) {
         dir.mkdirs();
    }
}
catch(Exception e){
    Log.w("creating file error", e.toString());
}
Committal answered 19/12, 2012 at 13:57 Comment(1)
>> First of all you shouldn't use a file path with "/mnt/sdcard/test" >> It's OK, because it's example code. In fact, it's part of file manager and I'm trying to create directory with user-defined path. So, I don't use hardcoded "/mnt/sdcard/" path in real code.Procrustes
R
1

Try to use

    String rootPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/test/";
            File file=new File(rootPath);
if(!file.exists()){
file.mkdirs();
}
Rhodic answered 19/12, 2012 at 13:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.