How to find sub-directories in a directory/folder?

前端 未结 3 1463
北荒
北荒 2020-12-18 18:31

I\'m looking for a way to get all the names of directories in a given directory, but not files.

For example, let\'s say I have a folder called Parent, a

相关标签:
3条回答
  • 2020-12-18 19:07

    You can use String[] directories = file.list() to list all file names, then use loop to check each sub-files and use file.isDirectory() function to get subdirectories.

    For example:

    File file = new File("C:\\Windows");
    String[] names = file.list();
    
    for(String name : names)
    {
        if (new File("C:\\Windows\\" + name).isDirectory())
        {
            System.out.println(name);
        }
    }
    
    0 讨论(0)
  • 2020-12-18 19:18
    public static void displayDirectoryContents(File dir) {
        try {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    System.out.println("Directory Name==>:" + file.getCanonicalPath());
                    displayDirectoryContents(file);
                } else {
                    System.out.println("file Not Acess===>" + file.getCanonicalPath());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    }

    ====inside class/Method provide File=URL ======

        File currentDir = new File("/home/akshya/NetBeansProjects/");
        displayDirectoryContents(currentDir);
    }
    
    0 讨论(0)
  • 2020-12-18 19:25

    If you are on java 7, you might wanna try using the support provided in

    package java.nio.file 
    

    If your directory has many entries, it will be able to start listing them without reading them all into memory first. read more in the javadoc: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path,%20java.lang.String)

    Here is also that example adapted to your needs:

    public static void main(String[] args) {
        DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path file) throws IOException {
                return (Files.isDirectory(file));
            }
        };
    
        Path dir = FileSystems.getDefault().getPath("c:/");
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {
            for (Path path : stream) {
                // Iterate over the paths in the directory and print filenames
                System.out.println(path.getFileName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
提交回复
热议问题