File.mkdir() and mkdirs() are creating file instea

2019-04-08 02:16发布

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?

4条回答
Bombasti
2楼-- · 2019-04-08 02:33

Try to use

    String rootPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/test/";
            File file=new File(rootPath);
if(!file.exists()){
file.mkdirs();
}
查看更多
来,给爷笑一个
3楼-- · 2019-04-08 02:34

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());
}
查看更多
趁早两清
4楼-- · 2019-04-08 02:53

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();
查看更多
Bombasti
5楼-- · 2019-04-08 02:54

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();
查看更多
登录 后发表回答