[英]Fast listing files in a directory and all of its subdirectories
I need to find all files in a directory and all of its subdirectories (except some). 我需要在目录及其所有子目录(某些目录除外)中找到所有文件。
Currently I'm using this method: 目前,我正在使用这种方法:
public static Collection<File> listFiles(File directory,FilenameFilter filter,boolean recurse){
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
if(entries!=null){
for (File entry : entries){
if (filter == null || filter.accept(directory, entry.getName())){
files.add(entry);
}
if (recurse && entry.isDirectory()){
files.addAll(listFiles(entry, filter, recurse));
}
}
}
return files;
}
and using it like this: 并像这样使用它:
this.foundFiles=listFiles(new File(this.BaseDirectory), new FilenameFilter() {
public boolean accept(File dir, String name) {
boolean res=true;
if(name.endsWith(".pdf")){
if(!dir.getPath().endsWith("done")){
if((workingFile!=null && (dir.getPath().equals(workingFile.getParent()) && name.equals(workingFile.getName())))){
res=false;
}else{
try {
ArrayList<String> AuthFolders = DB.getGroupAuthFoldersArray();
for(String folder:AuthFolders){
if(dir.getPath().startsWith(BaseDirectory+File.separator+folder)){
res=true;
break;
}else{
res=false;
}
}
} catch (SQLException ex) {
Logger.getLogger(scanner.class.getName()).log(Level.SEVERE, null, ex);
res=false;
} catch (InterruptedException ex) {
Logger.getLogger(scanner.class.getName()).log(Level.SEVERE, null, ex);
res=false;
}
}
}else{
res=false;
}
}else{
res=false;
}
return res;
}
}, true);
But this is too slow! 但这太慢了! I have about 3000 files in the directory and it takes 10-15 mins (!!) for this method to find them all.
我的目录中大约有3000个文件,这种方法需要10到15分钟(!!)才能找到所有文件。
How Can I do this fast? 我该如何快速完成?
I'm thinking about using org.apache.commons.io.FileUtils.listfiles
method. 我正在考虑使用
org.apache.commons.io.FileUtils.listfiles
方法。 Is there a faster way? 有没有更快的方法?
Thanks 谢谢
Use Files.walkFileTree
in Java 7, which is faster than listFiles
because it uses streaming. 使用
Files.walkFileTree
在Java 7中,这是快于listFiles
因为它使用流媒体。 Read the tutorial for more information. 阅读教程以获取更多信息。
} catch (SQLException ex) {
这不属于旨在执行目录列表的类!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.