Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / Java

Get List of Folders in Java

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
1 Feb 2015CPOL 31.2K   2  
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

This article was originally posted at http://maximumdeveloper.com/get-list-of-folders-in-java

License

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


Written By
Software Developer
Norway Norway
My name is Gjermund Bjaanes. I am 25 years old, born and raised in Norway. I am a developer, geek and enthusiast in general. I’m passionate about programming and software engineering in general. Currently I focus on web development and mobile development on my free time.

I am a software engineer and developer by trade and by passion.

I have always had a very enthusiastic interest for computers, dated to when I was little. It became an obsession for programming, IT, gadgets and new technology. I love being a developer, and that is why I do it as much as I can!

Other than that; In my spare time I like to code, read, cook, hang out with friends and to work out.

Comments and Discussions

 
-- There are no messages in this forum --