I want to search a file(without knowing the full name) in a specific directory using Java NIO and 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;
}
});
}
Reading some tutorial I did this. I just want to return string if I find(first) file with given glob String.
if (pathMatcher.matches(path)) {
return path.toString();
}
There are two things to be changed:
To "find(first) file with given glob String" you need to finish walking the tree if you encounter the file, thus if a match is given. And you need to store the matching path as result. The result of Files.walkFileTree
itself is the "the starting file" (JavaDoc). That's a Path
pointing to the 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();
}
If there is no match then the resulting String
is empty.
EDIT:
Using Files.walk
we can implement the search with less code still using a glob expression based matcher:
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();
}
The Optional
as result shows that there may be no match.