[英]How to access directory “/storage/emulated”
我在Marshmallow(api 23) 。
我已經聲明了相對權限並在運行時請求這些權限。 我通過Environment.getExternalStorageDirectory()
獲得了external storage directory
- “/ storage / emulated / 0”。 使用這個文件實例(這里我稱之為extF
), extF.listFiles()
不為null。 但是extF.getParentFile().listFiles()
返回null。
在adb shell中,我檢查了"/storage/emulated"
目錄,並且確實有兩個子目錄:
0
obb
那么,為什么我Marshmallow(api23)
File.listFiles()
在Marshmallow(api23)
上獲取"/storage/emulated"
的子文件? 謝謝你的解釋。
你可以像這樣在marshmallow中獲取你的文件列表
//this function will check for runtime permission so Add this block in your OnCreate() Method
if(checkandRequestPermission()) {
File sdCardRoot = Environment.getExternalStorageDirectory();
Log.w("SDCardRoot", "" + sdCardRoot);
File yourDir = new File(sdCardRoot, "/yourFolderName");
// This will check if directory is exist or not
if (!yourDir.exists()) {
yourDir.mkdirs();
}
if(yourDir.isDirectory()){
File[] content = yourDir.listFiles();
for(int i = 0; i<content.length;i++){
// Your List of Files
Log.w("List", "" + String.valueOf(content[i]));
}
}
現在如果你使用的是api level 23,那么你需要像這樣添加運行時權限
// Declare this function to check for runtime permission
private boolean checkandRequestPermission(){
int storageread = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> listpermissionNeeded = new ArrayList<>();
if (storageread != PackageManager.PERMISSION_GRANTED) {
listpermissionNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!listpermissionNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listpermissionNeeded.toArray(new String[listpermissionNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
在Manifiest中添加此權限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
那么,為什么我不能通過File.listFiles()獲取這些文件?
您的應用對該目錄沒有讀取權限。
可能是Manifest中的Permissions問題:android:name =“android.permission.READ_EXTERNAL_STORAGE”*
如果這不起作用,只需確保路徑是否正確
下面的代碼對我有用
File f = new File(Environment.getExternalStorageDirectory()+ "");
if (f.exists()) {
File[] dff= f.listFiles();
}else{
Logs.debug("siz","Files not existed.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.