2017-06-14 48 views
-1

我現在在android中構建一個文件共享應用程序,我試圖讓所有的文件在某個目錄(在我的情況下,它是MP3目錄)。而我正在使用函數File.listFiles()這樣做,它沒有任何理由返回null。閱讀目錄的文件返回空數組

directorys = new File(Environment.getExternalStorageDirectory().toString()+"/mp3"); 
     Log.d(TAG,directorys.listFiles().length+""); 

之後它給出了一個異常listFiles是一個空數組? BTW我已經使用這個權限

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

回答

0

嘗試

String path = Environment.getExternalStorageDirectory().toString()+"/mp3"; 
Log.d("Files", "Path: " + path); 
File directory = new File(path); 
File[] files = directory.listFiles(); 
Log.d("Files", "Size: "+ files.length); 
for (int i = 0; i < files.length; i++) 
{ 
    Log.d("Files", "FileName:" + files[i].getName()); 
} 

和棉花糖及以上版本的代碼,你需要添加權限programaticaly

public boolean requestForPermission() { 

    boolean isPermissionOn = true; 
    final int version = Build.VERSION.SDK_INT; 
    if (version >= 23) { 
     if (!canAccessExternalSd()) { 
      isPermissionOn = false; 
      requestPermissions(EXTERNAL_PERMS, EXTERNAL_REQUEST); 
     } 
    } 

    return isPermissionOn; } 

public boolean canAccessExternalSd() { 
    return (hasPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)); } 

private boolean hasPermission(String perm) { 
    return (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, perm)); 

} 
+0

它仍然返回null .. –

+0

我不認爲它會,你可以測試它 –

+0

我做了,它仍然 –