Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Get List of Folders in Java

5.00/5 (2 votes)
1 Feb 2015CPOL 31.7K  
Get list of folders in Java

If you need to list only the folders in some directory (and not folders AND files), that can be done without too much effort in Java.

The key is use File’s listFiles with a FileFilter:

Java
public File[] listFiles(FileFilter filter)

You can create an anonymous class like this to pass to your File object.

Java
FileFilter directoryFileFilter = new FileFilter() {
    public boolean accept(File file) {
        return file.isDirectory();
    }
};

When you now call listFiles with the “directoryFileFilter”, you will get a list of the folders inside your File object.

Java
File directory = new File("/some/directory/");
directory.listFiles(directoryFileFilter);

It's pretty straight-forward.

You could easily produce a function that takes a directory path (as a string) and make it return a list of folders inside that directory.

Java
public List<String> findFoldersInDirectory(String directoryPath) {
    File directory = new File(directoryPath);
	
    FileFilter directoryFileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
		
    File[] directoryListAsFile = directory.listFiles(directoryFileFilter);
    List<String> foldersInDirectory = new ArrayList<String>(directoryListAsFile.length);
    for (File directoryAsFile : directoryListAsFile) {
        foldersInDirectory.add(directoryAsFile.getName());
    }

    return foldersInDirectory;
}

Credit to: http://www.avajava.com/tutorials/lessons/how-do-i-use-a-filefilter-to-display-only-the-directories-within-a-directory.html

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)