Java NIO2 - Return a recursive Collection<Path>
-
17-05-2021 - |
Question
I am looking at the new functionality in Java7. I want to get a Collection objects returned given a specific input directory.
Currently I am using using (org.apache.commons.io)
Collection<File> files = FileUtils.listFiles(myInputFile, ...);
Instead I would like to do something like:
Collection<Path> paths = listPathsUsingJava7(myInputPath, ...);
However, I don't see anything specific about doing it in the examples/docs out there. I see DirectoryStreams, which don't seem to do recursion. I also see Vistors which make you take action on the current object instead of adding it to a Collection.
Does anyone have a Java7 example of doing this the correct way?
Thanks!
Solution
next JDK7 code will add all files in folder and subfolders to files
.
final List<Path> files = new ArrayList<>();
Files.walkFileTree(Paths.get(myInputPath), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
files.add(file);
return FileVisitResult.CONTINUE;
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow