Java 8 List All Files in Directory

List All Files in Directory

Files.list Method Return a lazily populated Stream, the elements of which are the entries in the directory.

We Can use the stream operations to find Specific Files, List file matching certain criteria, List filenames in sorted order etc.

Example 1: List All Files in Directory
List All Files in Directory
1
2
3
4
5
6
7
8

public static void main(String[] args) throws IOException {

try(Stream<Path> list = Files.list(Paths.get("C:\\Program Files\\"));)
{
list.forEach(System.out::println);
}
}
Example 2: List All Files in Directory Starting with A
List All Files in Directory Starting with A
1
2
3
4
5
6
7
8
9
10
11
12
13
14

public static void main(String[] args) throws IOException {

try (Stream<Path> list = Files.list(Paths.get("C:\\Program Files\\"))) {
List<String> fileList = list.map(path -> path.getFileName()
.toString())
.filter(name -> name.startsWith("A"))
.sorted()
.collect(Collectors.toList());
fileList.forEach(System.out::println);
}

}

Example 3: List Files Only
List Files Only
1
2
3
4
5
6
7
8
9
10
11
12

public static void main(String[] args) throws IOException {

try (Stream<Path> list = Files.list(Paths.get("C:\\Program Files\\"))) {
List<String> fileList = list.filter(path->path.toFile().isFile())
.map(path -> path.getFileName().toString())
.collect(Collectors.toList());
fileList.forEach(System.out::println);
}

}

Example 4: List Directory Only
List Directory Only
1
2
3
4
5
6
7
8
9
10
11
12

public static void main(String[] args) throws IOException {

try (Stream<Path> list = Files.list(Paths.get("C:\\Program Files\\"))) {
List<String> fileList = list.filter(path->path.toFile().isDirectory())
.map(path -> path.getFileName().toString())
.collect(Collectors.toList());
fileList.forEach(System.out::println);
}

}

Example 5: List Hidden files Only
List Hidden files Only
1
2
3
4
5
6
7
8
9
10
11
12

public static void main(String[] args) throws IOException {

try (Stream<Path> list = Files.list(Paths.get("C:\\Program Files\\"))) {
List<String> fileList = list.filter(path->path.toFile().isHidden())
.map(path -> path.getFileName().toString())
.collect(Collectors.toList());
fileList.forEach(System.out::println);
}

}

Note

Files.list Method Return a lazily populated Stream for the directory.
It does not return Stream for the nested directory. For that, we Can use File.walk . Will discuss that in next chapter.

Share Comments