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