Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively list all files within a directory using nio.file.DirectoryStream;

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()); } 
like image 882
Danny Rancher Avatar asked Jan 08 '14 04:01

Danny Rancher


People also ask

How do I list all files in a directory recursively?

Linux recursive directory listing using ls -R command. The -R option passed to the ls command to list subdirectories recursively.

Are files walk recursive?

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.

Which method returns the directories in the current directory supports filtering and recursive listing?

GetDirectories() Returns the subdirectories of the current directory.


2 Answers

Java 8 provides a nice way for that:

Files.walk(path) 

This method returns Stream<Path>.

like image 138
Vladimir Petrakovich Avatar answered Sep 23 '22 07:09

Vladimir Petrakovich


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);         }     } } 
like image 36
Evgeniy Dorofeev Avatar answered Sep 23 '22 07:09

Evgeniy Dorofeev