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

纵然是瞬间 提交于 2019-11-29 05:31:33

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

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();
    }
}
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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!