Reputation: 1515
I have a scenario where I need to get the folder name and filename using Files.walk simultaneously.
Below is the directory: c:\files\foldername1\filename1.txt c:\files\foldername2\filename2.txt
Following code gives output which are file names
c:\\files\foldername1\\filename1.txt
c:\\files\foldername2\\filename2.txt
try (Stream<Path> walk = Files.walk(Paths.get("c:\\files"))) {
List<String> result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
}
Following code gives output which is directories
c:\\files\foldername1
c:\\files\foldername2
try (Stream<Path> walk = Files.walk(Paths.get("c:\\files"))) {
List<String> result = walk.filter(Files::isDirectory)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
}
Is there a way to get folder name and file name using one filter at the same time.
Upvotes: 0
Views: 1186
Reputation: 3366
This:
Map<Path, List<Path>> files = walk.filter(Files::isRegularFile).collect(Collectors.groupingBy(Path::getParent))
will give you a Map
of List
s to Path
s. The keys of the map will be the parent directory paths. The values of the map will be lists of all the files which are included in the directory which corresponds to the key of the map entry.
Upvotes: 2