mkdir()创建的目录被视为文件

时间:2016-10-20 11:55:43

标签: java android

我有问题。我正在尝试更改用户数据的应用程序目录的名称。我在代码中更改它并从手机中删除它以检查应用程序是否创建了具有正确名称的新代码。然后麻烦开始了。目录已创建,但当我尝试在Windows资源管理器中打开目录时,它被视为文件。 mkdir()为每个目录返回true

当我检查Environment.getExternalStorageDirectory().canWrite()时,它也会返回true。我的gradle配置

  compileSdkVersion 23    
  minSdkVersion 23    
  targetSdkVersion 23 

(我想降级到minSdkVersion 21)。在清单中我有:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

一些代码(已更新):

File appDir = new File (Environment.getExternalStorageDirectory().getAbsolutePath()+"/Trainer app/");
File modelsDir = new File(appDir.getAbsolutePath()+"/Modele/");
File pdfDir = new File(appDir.getAbsolutePath()+"/Ostatnio wygenerowany trening/");
boolean result;
if(!appDir.exists()){
Log.wtf("StorageState",""+Environment.getExternalStorageState()+" Write: "+Environment.getExternalStorageDirectory().canWrite());
Log.wtf("TEST DIR","Create appDir "+result+" is dir: "+appDir.isDirectory());
Log.wtf("TEST DIR","Create appDir "+result);
MediaScannerConnection.scanFile(this, new String[]{appDir.toString()}, null, null);
}
//if(appDir.exists()&&!modelsDir.exists()){
if(!modelsDir.exists()){
//Log.wtf("MODELDIR", "" + modelsDir.mkdir() + " Path: " + modelsDir.getAbsolutePath());
result=modelsDir.mkdirs();
Log.wtf("TEST DIR", "Create modelDir "+result+" is dir: "+modelsDir.isDirectory());
MediaScannerConnection.scanFile(this, new String[]{modelsDir.toString()}, null, null);
}
//if(appDir.exists()&&!pdfDir.exists()){
if(!pdfDir.exists()){
//Log.wtf("PDFDIR", "" + pdfDir.mkdir() + " Path: " + pdfDir.getAbsolutePath());
result=pdfDir.mkdirs();
Log.wtf("TEST DIR","Create pdfDir "+result+" is dir: "+pdfDir.isDirectory());
MediaScannerConnection.scanFile(this, new String[]{pdfDir.toString()}, null, null);
}

更新:现在我无权在外部存储上写字。当我将minSdk更改为21并将targetSdk更改为22时,我有权利,但即使使用您的提示我仍然无法创建目录

1 个答案:

答案 0 :(得分:1)

问题就在这里

File appDir = new File (path,file_name);

File appDir = new File (Environment.getExternalStorageDirectory(),"Trainer app");

并且此appDir.mkdir()将在存储目录的默认路径下创建名为Trainer app的文件

所以你想创建像Environment.getExternalStorageDirectory()/Trainer app这样的目录,然后像这样做

String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Trainer app/";

File dictionary = new File(path);
if (!dictionary.exists()) {
   dictionary.mkdirs();
}

稍后创建文件

File file1 = new File(dictionary, filename);

更新:您需要实施运行时权限模型以获取用户访问存储的权限,请尝试此link for implementation