Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

android - List all the files from all the folder in a single list

Hi I am looking for the solution to list all the files from root/Android device.

Suppose there are 3 folder inside root directory,but I want to display all the files in all of these folder in a single list..

Now If am using

       File f=new File("/sdcard");

Then it will list all the files from the sdcard folder only..and If I will use

       File f=new File("/download");

Then it will list all the files from download folder only ..and if I will use

       File f=new File("/");

Then it will list only root direcoty files...not the files inside /sdcard or /download..

So what steps shall I follow to list all the files with a filter to list only .csv files from all the folder inside root.

Thanks..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

 .....
 List<File> files = getListFiles(new File("YOUR ROOT")); 
 ....
 private List<File> getListFiles(File parentDir) {
    ArrayList<File> inFiles = new ArrayList<File>();
    File[] files = parentDir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            inFiles.addAll(getListFiles(file));
        } else {
            if(file.getName().endsWith(".csv")){
                inFiles.add(file);
            }
        }
    }
    return inFiles;
}

or variant without recursion:

private List<File> getListFiles2(File parentDir) {
    List<File> inFiles = new ArrayList<>();
    Queue<File> files = new LinkedList<>();
    files.addAll(Arrays.asList(parentDir.listFiles()));
    while (!files.isEmpty()) {
        File file = files.remove();
        if (file.isDirectory()) {
            files.addAll(Arrays.asList(file.listFiles()));
        } else if (file.getName().endsWith(".csv")) {
            inFiles.add(file);
        }
    }
    return inFiles;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...