EN
Java - find file by filename inside directory
0
points
In this article, we would like to show you how toΒ find a file by filename in the specified directoryΒ inΒ Java.
Project structure
/C/
βββ directory/
βββ subdirectory1/
β βββ file.txt
βββ subdirectory2/
Practical examples
In this example, we use Files.find()
method to search for file.txt
starting from C:/directory
folder.
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) throws IOException {
Path directoryPath = Paths.get("C:\\directory");
String filename = "file.txt";
List<Path> result;
try (Stream<Path> pathStream = Files.find(directoryPath,
Integer.MAX_VALUE,
(path, basicFileAttributes) ->
path.getFileName().toString().equalsIgnoreCase(filename))
) {
result = pathStream.collect(Collectors.toList());
}
result.forEach(System.out::println);
}
}
Output:
C:\directory\subdirectory1\file.txt