Java, List only subdirectories from a directory, not files
In Java, How do I list only subdirectories from a directory?
I'd like to use the java.io.File functionality, what is the best method in Java for doing this?
Solution 1:
You can use the File class to list the directories.
File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
System.out.println(Arrays.toString(directories));
Update
Comment from the author on this post wanted a faster way, great discussion here: How to retrieve a list of directories QUICKLY in Java?
Basically:
- If you control the file structure, I would try to avoid getting into that situation.
- In Java NIO.2, you can use the directories function to return an iterator to allow for greater scaling. The directory stream class is an object that you can use to iterate over the entries in a directory.
Solution 2:
A very simple Java 8 solution:
File[] directories = new File("/your/path/").listFiles(File::isDirectory);
It's equivalent to using a FileFilter (works with older Java as well):
File[] directories = new File("/your/path/").listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory();
}
});
Solution 3:
@Mohamed Mansour you were almost there... the "dir" argument from that you were using is actually the curent path, so it will always return true. In order to see if the child is a subdirectory or not you need to test that child.
File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
System.out.println(Arrays.toString(directories));
Solution 4:
In case you're interested in a solution using Java 7 and NIO.2, it could go like this:
private static class DirectoriesFilter implements Filter<Path> {
@Override
public boolean accept(Path entry) throws IOException {
return Files.isDirectory(entry);
}
}
try (DirectoryStream<Path> ds = Files.newDirectoryStream(FileSystems.getDefault().getPath(root), new DirectoriesFilter())) {
for (Path p : ds) {
System.out.println(p.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}