Using Java 8+ features we can write the code in few lines:
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
returns a Stream<Path>
which is "walking the file tree rooted at" the given searchDirectory
. To select the desired files only a filter is applied on the Stream
files
. It compares the file name of a Path
with the given fileName
.
Note that the documentation of Files.walk
requires
This method must be used within a try-with-resources statement or
similar control structure to ensure that the stream's open directories
are closed promptly after the stream's operations have completed.
I'm using the try-resource-statement.
For advanced searches an alternative is to use a 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());
}
}
An example how to use it to find a certain file:
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);
}
More about it: Oracle Finding Files tutorial