简体   繁体   中英

Java nio, get all subfolders of some folder

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!

    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);

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM