我需要用Java开发一个文件扫描器,具有以下选项/参数:
- 一个目录
- 一个或多个模式,如*.xml、*.txt、*test.csv
- 递归扫描开关
我认为最好的方法是类似于以下方式:
public class FileScanningTest {
public static void main(String[] args) throws IOException {
String directory = "C:\\tmp\\scanning\\";
String glob = "**/*.xml";
Boolean rekursiv = false;
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:"+glob);
Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(path)) {
System.out.println(path);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
}
}
我不明白为什么我必须在实际模式前面放置“**/”。同时这确实使扫描递归。如果我删除 **/,应用程序将不再找到任何内容。 https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob 告诉我们 ** 表示递归,但是如果我去掉它为什么它就不能工作呢?
有人能给我一个提示吗?
谢谢大家,祝你们周末愉快。