如何获取Android目录中文件的列表?

时间:2019-06-26 17:00:34

标签: java android directory

我想列出目录中的所有图像以创建图库。下面的示例正在使用Intent获取目录路径。

我尝试了listFiles()方法,但是它返回null。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Permision Request
    ActivityCompat.requestPermissions(MainActivity.this,
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            1);
    initialize();
}

//For the Intent to get Folder
private void initialize() {
    Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    i.addCategory(Intent.CATEGORY_DEFAULT);
    startActivityForResult(Intent.createChooser(i, "Choose directory"), 9999);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case 9999:
            //File myFile = new File(data.getData().toString());
            String path = data.getData().toString();
            //View the path
            Log.i("Test", "Result URI " + path);
            Toast.makeText(getApplicationContext(), "Result URI " +data.getData().toString(), Toast.LENGTH_LONG).show();

            //Creating new File for the directory
            File directory = new File(path);
            File[] files = directory.listFiles();

            Log.d("Files", "Size: "+ files.length);
            for (int i = 0; i < files.length; i++)
            {
                //Show the name of the files in the directory
                Log.d("Files", "FileName:" + files[i].getName());
            }

            break;
    }
}

清单中的我也有权读取外部存储空间

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

预期返回目录中文件的名称,但返回此错误:

Caused by: java.lang.NullPointerException: Attempt to get the length of null array
    at cu.edu.cujae.citi.folderpicker.MainActivity.workWithFile(MainActivity.java:59)
    at cu.edu.cujae.citi.folderpicker.MainActivity.onActivityResult(MainActivity.java:49)
    at android.app.Activity.dispatchActivityResult(Activity.java:6932)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132) 
    at android.app.ActivityThread.-wrap20(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6119) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

1 个答案:

答案 0 :(得分:0)

  

下面的示例正在使用Intent来获取目录路径。

否,它正在使用ACTION_OPEN_DOCUMENT_TREE来获取文档树。这可能代表文件系统上的目录,也可能不代表。

处理Uri返回的ACTION_OPEN_DOCUMENT_TREE的最简单方法是使用DocumentFile.fromTreeUri()。然后,您可以对其调用listFiles(),以获取指向该树中文档(和子树)的DocumentFile对象。