简体   繁体   中英

How to get list of file names in downloads folder?

I tried this:

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

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

But it shows null. I have given permissions for read and write in manifest.

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

The READ_EXTERNAL_STORAGE is dangerous permission You need to ask it runtime permission

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

You need to ask runtime permission

and also try this

Try this

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));

    }
}
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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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