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
:
public File[] listFiles(FileFilter filter)
You can create an anonymous class like this to pass to your File
object.
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.
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.
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
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.