您知道在哪里可以找到在Java中实现 FileIterator (或类似内容)的库吗?让它像以下(未经检查的代码)一样工作会很高兴:
Iterator it = new FileIterator();
it.addDirectory("../some-dir/");
it.addInclude("**/*.java");
it.addExclude(".svn/**");
while (it.hasNext()) {
File f = it.next();
System.out.println("File found: " + f);
}
在Maven FileSet中实现了类似的功能,但我不认为将Maven JAR添加到我的项目中是个好主意:)
答案 0 :(得分:4)
查看org.apache.commons.io.FileUtils.iterateFiles(..)
Iterator<File> iterateFiles(File directory,
String[] extensions,
boolean recursive)
答案 1 :(得分:1)
您可以在Commons-IO中使用DirectoryWalker,例如:
public class FileCleaner extends DirectoryWalker {
public FileCleaner() {
super();
}
public List clean(File startDirectory) {
List results = new ArrayList();
walk(startDirectory, results);
return results;
}
protected boolean handleDirectory(File directory, int depth, Collection results) {
// delete svn directories and then skip
if (".svn".equals(directory.getName())) {
directory.delete();
return false;
} else {
return true;
}
}
protected void handleFile(File file, int depth, Collection results) {
// delete file and add to list of deleted
file.delete();
results.add(file);
}
}
其他示例可在http://commons.apache.org/io/api-2.0/index.html?org/apache/commons/io/FileUtils.html
找到