6

How could I get all subfolders of some folder? I would use JDK 8 and nio.

picture

for example, for folder "Designs.ipj" method should return {"Workspace", "Library1"}

Thank you in advance!

4
  • 2
    You should edit your post and include the image in your question. Eventually external links become unavailable at some point and as such preventing future users to benefit from your question. Commented Jul 8, 2016 at 14:26
  • docs.oracle.com/javase/tutorial/essential/io/dirs.html#listdir Commented Jul 8, 2016 at 14:28
  • hmmm do you need non-blocking IO for this ? Commented Jul 8, 2016 at 14:29
  • I couldn't add picture because my rating is too low. Commented Jul 8, 2016 at 14:44

2 Answers 2

17
 List<Path> subfolder = Files.walk(folderPath, 1) .filter(Files::isDirectory) .collect(Collectors.toList()); 

it will contains folderPath and all subfolders in depth 1. If you need only subfolders, just add:

subfolders.remove(0); 
Sign up to request clarification or add additional context in comments.

1 Comment

DirectoryStream<Path> paths = Files.newDirectoryStream(folder, entry -> Files.isDirectory(entry)); much shorter
-2

You have to read all the items in a folder and filter out the directories, repeating this process as many times as needed.

To do this you could use listFiles()

File folder = new File("your/path"); Stack<File> stack = new Stack<File>(); Stack<File> folders = new Stack<File>(); stack.push(folder); while(!stack.isEmpty()) { File child = stack.pop(); File[] listFiles = child.listFiles(); folders.push(child); for(File file : listFiles) { if(file.isDirectory()) { stack.push(file); } } } 

see Getting the filenames of all files in a folder A simple recursive function would also work, just make sure to be wary of infinite loops.

However I am a bit more partial to DirectoryStream. It allows you to create a filter so that you only add the items that fit your specifications.

DirectoryStream.Filter<Path> visibleFilter = new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path file) { try { return Files.isDirectory(file)); } catch(IOException e) { e.printStackTrace(); } return false; } try(DirectoryStream<Path> stream = Files.newDirectoryStream(directory.toPath(), visibleFilter)) { for(Path file : stream) { folders.push(child); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.