2017-06-13 133 views
0

我試圖在Android設備的SDcard上的Downloads目錄下創建一個文件夾。我已經在清單中聲明瞭<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />Android創建目錄

這裏是我的代碼:

String state = Environment.getExternalStorageState(); 
    if (!Environment.MEDIA_MOUNTED.equals(state)) { 
     Log.e("file writer", "Directory not writeable"); 
     Toast.makeText(this, "Not writeable.", 
       Toast.LENGTH_SHORT).show(); 
    } 

    File dir = new File(Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_DOWNLOADS), "myfolder"); 
    dir.mkdirs(); 
    if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); } 

我得到的「目錄沒有創建」的錯誤,顯然有沒有文件夾,我打算在那裏是一個。

+0

您有權要求運行時間權限也如果你正在運行的應用程序在Android 6.0及以上 –

回答

0

您取得的Android許可6+你應該問用戶,試試這個

 if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_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(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE); 
      // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request. 
     } 
    } 
+0

運行時權限適用於Android 6+,而不是7+ –

+0

謝謝你是的,你是對的 – Meikiem

+0

我認爲你一定是對的。完全相同的代碼適用於我的Android 5.1測試設備,但不適用於運行6.0.1的代碼 – cashmoneyscience

0

你試過嗎?

String state = Environment.getExternalStorageState(); 
if (!Environment.MEDIA_MOUNTED.equals(state)) { 
    Log.e("file writer", "Directory not writeable"); 
    Toast.makeText(this, "Not writeable.", 
      Toast.LENGTH_SHORT).show(); 
}else{ 

File dir = new File(Environment.getExternalStoragePublicDirectory(
     Environment.DIRECTORY_DOWNLOADS), "myfolder"); 
dir.mkdirs(); 
if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); } } 
0

試試這個代碼

File rootPath = new File(Environment.getExternalStorageDirectory(), "Download/myfolder"); 
if (!rootPath.exists()) 
     rootPath.mkdirs(); 

希望它的工作