2016-08-11 71 views
0

我想讓設備中的目錄和文件。android File.mkdirs()總是返回false

但是當File.mkdirs()總是返回false ... 我不知道爲什麼!

我甚至已經在清單中添加的權限是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="pkg.pkg.pkg"> 

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

,這是我的代碼:

File directory = null; 
File file = null; 
String dir = ""; 
String folderName = "test"; 

String sdcard = Environment.getExternalStorageState(); 

if(sdcard.equals(Environment.MEDIA_MOUNTED)){ 
    dir = Environment.getExternalStorageDirectory().getAbsolutePath(); 
} else { 
    dir = Environment.getRootDirectory().getAbsolutePath(); 
} 

directory = new File(dir, folderName); 

if(!directory.exists()) { 
    directory.mkdirs(); // return false here. 
} 

if(directory.isDirectory()){ 

    file = new File(directory.getAbsolutePath(), fileName); 
    if(file.exists()){ 
     String tempFileName = et_export.getText().toString(); 

     // Check duplicate file name 
     for(int i=1;;i++){ 
      fileName = tempFileName + " (" + i + ").png"; 
      file = new File(directory.getAbsolutePath(), fileName); 
      if(!file.exists()) break; 
     } // for 

    } // if(file.exists()) 

} // if(directory.isDirectory()) 

什麼問題...?

+0

片斷,你可以在這裏放一些日誌。 – Vito

+0

'directory.mkdirs();'更好:'if(!directory.mkdirs())return;'你還可以顯示一個敬酒。 – greenapps

回答

0

https://developer.android.com/training/permissions/requesting.html

在在Android 6.0(API級別23)開始,用戶授予權限的應用程序應用程序運行時,而不是當他們安裝應用程序。

您需要手動編寫權限授予部分(除了在清單中定義它)。

以下是developer.android.com

if (ContextCompat.checkSelfPermission(thisActivity, 
       Manifest.permission.WRITE_EXTERNAL_STORAGE) 
     != PackageManager.PERMISSION_GRANTED) { 

    // Should we show an explanation? 
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, 
      Manifest.permission.WRITE_EXTERNAL_STORAGE)) { 

     // Show an expanation to the user *asynchronously* -- don't block 
     // this thread waiting for the user's response! After the user 
     // sees the explanation, try again to request the permission. 

    } else { 

     // No explanation needed, we can request the permission. 

     ActivityCompat.requestPermissions(thisActivity, 
       new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
       MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); 

     // MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE is an 
     // app-defined int constant. The callback method gets the 
     // result of the request. 
    } 
} 
+0

謝謝,它的工作。 –