我正在编写一种方法来获取特定的文件类型,例如pdf或txt,从文件夹和子文件夹获得,但我缺乏解决这个问题的方法。这是我的密码
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}我的当前方法列出了所有文件,但我需要特定的文件。
发布于 2013-12-05 13:47:32
if(file.getName().endsWith(".pdf")) {
//it is a .pdf file!
}/***/
发布于 2013-12-05 13:49:58
对于经过筛选的列表,不需要通过子目录进行递归,只需执行以下操作:
directory.listFiles(new FilenameFilter() {
boolean accept(File dir, String name) {
return name.endsWith(".pdf");
}});为了提高效率,您可以提前创建FilenameFilter,而不是为每个调用创建。
在这种情况下,因为您也想扫描子文件夹,所以没有必要过滤文件,因为您仍然需要检查子文件夹。事实上,你差点就到了:
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
if (file.getName().endsWith(".pdf")) {
System.out.println(file.getAbsolutePath());
}
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}发布于 2013-12-05 13:51:56
尝试在函数FilenameFilter中使用http://docs.oracle.com/javase/6/docs/api/java/io/FilenameFilter.html接口
http://www.mkyong.com/java/how-to-find-files-with-certain-extension-only/ -用于具有扩展筛选器的代码
https://stackoverflow.com/questions/20401610
复制相似问题