CoveredEe:
私は、Java NIOとグロブを使用して、特定のディレクトリ内の(完全な名前を知らなくても)ファイルを検索したいです。
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;
}
});
}
私はこれをしなかったいくつかのチュートリアルを読みます。私はちょうど私が与えられたグロブ文字列で(最初の)ファイルを見つけた場合、文字列を返すようにしたいです。
if (pathMatcher.matches(path)) {
return path.toString();
}
ルシオ:
変更するには、2つのものがあります。
「に与えられたグロブ文字列で検索する(最初の)ファイル」あなたは試合が指定されているようならば、ファイルが発生した場合は、ツリーを歩いて完了する必要があります。そして、あなたは結果として一致するパスを格納する必要があります。結果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();
}
一致するものがない場合はその結果のはString
空です。
EDIT:
使用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();
}
Optional
一致が存在しないことがあり、結果として示します。