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!

M. Black
  • 73
  • 1
  • 4

2 Answers2

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);
Wsl_F
  • 832
  • 1
  • 7
  • 16
  • 1
    DirectoryStream paths = Files.newDirectoryStream(folder, entry -> Files.isDirectory(entry)); much shorter – lisyara May 18 '19 at 16:19
-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);
    }
}
Community
  • 1
  • 1