繁体   English   中英

如何访问目录“/ storage / emulated”

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM