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.
xxxxxxxxxx
1
/C/
2
└── directory/
3
├── subdirectory1/
4
│ └── file.txt
5
└── subdirectory2/
In this example, we use Files.find()
method to search for file.txt
starting from C:/directory
folder.
xxxxxxxxxx
1
import java.io.IOException;
2
import java.nio.file.Path;
3
import java.nio.file.Paths;
4
import java.nio.file.Files;
5
import java.util.List;
6
import java.util.stream.Stream;
7
import java.util.stream.Collectors;
8
9
10
public class Example {
11
12
public static void main(String[] args) throws IOException {
13
Path directoryPath = Paths.get("C:\\directory");
14
String filename = "file.txt";
15
List<Path> result;
16
17
try (Stream<Path> pathStream = Files.find(directoryPath,
18
Integer.MAX_VALUE,
19
(path, basicFileAttributes) ->
20
path.getFileName().toString().equalsIgnoreCase(filename))
21
) {
22
result = pathStream.collect(Collectors.toList());
23
}
24
result.forEach(System.out::println);
25
}
26
}
Output:
xxxxxxxxxx
1
C:\directory\subdirectory1\file.txt