I want to list all the FILES within the specified directory and subdirectories within that directory. No directories should be listed.
My current code is below. It does not work properly as it only lists the files and directories within the specified directory.
How can I fix this?
final List<Path> files = new ArrayList<>(); Path path = Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles"); try { DirectoryStream<Path> stream; stream = Files.newDirectoryStream(path); for (Path entry : stream) { files.add(entry); } stream.close(); } catch (IOException e) { e.printStackTrace(); } for (Path entry: files) { System.out.println(entry.toString()); }
Linux recursive directory listing using ls -R command. The -R option passed to the ls command to list subdirectories recursively.
Files. walk returns a stream that is lazily populated with Path by recursively walking the file tree rooted at a given starting file. The file tree is traversed depth-first.
GetDirectories() Returns the subdirectories of the current directory.
Java 8 provides a nice way for that:
Files.walk(path)
This method returns Stream<Path>
.
Make a method which will call itself if a next element is directory
void listFiles(Path path) throws IOException { try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { for (Path entry : stream) { if (Files.isDirectory(entry)) { listFiles(entry); } files.add(entry); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With