如何获取下载文件夹中的文件名列表?

时间:2018-01-03 12:11:55

标签: android

我试过了:

File f =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        System.out.println(f.list());
        System.out.println(f.listFiles().toString());

但它显示为null。 我已经在清单中给予了读写权限。

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

2 个答案:

答案 0 :(得分:1)

READ_EXTERNAL_STORAGE 危险权限您需要询问运行时权限

  

从Android 6.0(API级别23)开始,用户在应用运行时向应用授予权限,而不是在安装应用时授予权限。

您需要ask runtime permission

并尝试此

试试这个

private void getfiles() {
    String[] filenames = new String[0];
    ArrayList<String> fileArrayList = new ArrayList<>();
    File path = new File(Environment.getExternalStorageDirectory() + "/folder_name");
    if (path.exists()) {
        filenames = path.list();
    }
    for (int i = 0; i < filenames.length; i++) {
        fileArrayList.add(path.getPath() + "/" + filenames[i]);
        Log.e("fileArrayList", fileArrayList.get(i));

    }
}

答案 1 :(得分:1)

File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

List<String> files = getList(f);


private List<String> getList(File parentDir, String pathToParentDir) {
ArrayList<String> inFiles = new ArrayList<String>();
String[] fileNames = parentDir.list();

for (String fileName : fileNames) {
    if (fileName.toLowerCase().endsWith(".txt") || 
fileName.toLowerCase().endsWith(".rtf") || 
fileName.toLowerCase().endsWith(".doc") || 
fileName.toLowerCase().endsWith(".txd")) {
        inFiles.add(pathToParentDir + fileName);
    } else {
        File file = new File(parentDir.getPath() + "/" + fileName);
        if (file.isDirectory()) {
            inFiles.addAll(getList(file, pathToParentDir + fileName + "/"));
        }
    }
}

return inFiles;
}