PSi*_*ngh 5 java nio glob file
我想使用 Java NIO 和 glob 在特定目录中搜索文件(不知道全名)。
public static void match(String glob, String location) throws IOException {
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(
glob);
Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path,
BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(path)) {
System.out.println(path);
}
return FileVisitResult.CONTINUE;
}
});
}
Run Code Online (Sandbox Code Playgroud)
阅读一些教程我这样做了。如果我找到(第一个)具有给定 glob 字符串的文件,我只想返回字符串。
if (pathMatcher.matches(path)) {
return path.toString();
}
Run Code Online (Sandbox Code Playgroud)
有两点需要改变:
要“使用给定的 glob 字符串查找(第一个)文件”,如果遇到该文件,则需要完成遍历树,因此如果给出匹配项。并且您需要将匹配的路径存储为结果。结果Files.walkFileTree本身就是“起始文件”(JavaDoc)。这是一个Path指向location.
public static String match(String glob, String location) throws IOException {
StringBuilder result = new StringBuilder();
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(path)) {
result.append(path.toString());
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
});
return result.toString();
}
Run Code Online (Sandbox Code Playgroud)
如果没有匹配,则结果String为空。
编辑:
使用Files.walk我们可以使用基于全局表达式的匹配器以更少的代码实现搜索:
public static Optional<Path> match(String glob, String location) throws IOException {
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
return Files.walk(Paths.get(location)).filter(pathMatcher::matches).findFirst();
}
Run Code Online (Sandbox Code Playgroud)
在Optional作为结果表明,有可能是不匹配。