问题描述
我正在寻找从 root/Android 设备列出所有文件的解决方案.
Hi I am looking for the solution to list all the files from root/Android device.
假设根目录中有 3 个文件夹,但我想在一个列表中显示所有这些文件夹中的所有文件..
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..
现在如果我正在使用
File f=new File("/sdcard");
然后它将仅列出 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("/");
然后它只会列出根目录文件...而不是/sdcard 或/download 中的文件..
Then it will list only root direcoty files...not the files inside /sdcard or /download..
那么我应该遵循哪些步骤来列出所有带有过滤器的文件,以仅列出根目录中所有文件夹中的 .csv 文件.
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.
谢谢..
推荐答案
试试这个:
.....
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;
}
或没有递归的变体:
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;
}
这篇关于在一个列表中列出所有文件夹中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!