I am looking for the solution to list all the files from root/Android device.
Suppose there are three folders inside the root directory, but I want to display all the files in all of these folders 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 the root directory 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?
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 a 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;
}