Java 8以降の機能を使用して、数行でコードを記述できます。
protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(f -> f.getFileName().toString().equals(fileName))
.collect(Collectors.toList());
}
}
Files.walk
Stream<Path>
指定されたを「ルート化したファイルツリーを歩いている」aを返しますsearchDirectory
。目的のファイルを選択するには、フィルターのみがに適用されますStream
files
。Path
aのファイル名を指定された。と比較しますfileName
。
のドキュメントにはFiles.walk
が必要であることに注意してください
このメソッドは、try-with-resourcesステートメントまたは同様の制御構造内で使用して、ストリームの操作が完了した後、ストリームの開いているディレクトリがすぐに閉じられるようにする必要があります。
try-resource-statementを使用しています。
高度な検索の場合、別の方法はPathMatcher
:を使用することです。
protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(matcher::matches)
.collect(Collectors.toList());
}
}
特定のファイルを見つけるためにそれを使用する方法の例:
public static void main(String[] args) throws IOException {
String searchDirectory = args[0];
String fileName = args[1];
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
Collection<Path> find = find(searchDirectory, matcher);
System.out.println(find);
}
詳細:OracleFindingFilesチュートリアル