Reputation: 21170
I have a folder which consists of both datafiles (.txt
etc) and subfolders.
In Java, how would I accomplish getting the number of subfolders in any specified directory path?
(so excluding the datafiles; only counting the subfolders)
I have read about counting the number of .txt
files but can't seem to find anything about counting subfolders only.
I have no idea where to start but to give you an idea:
String directory = "C:\Users\ . \Desktop\ . \workspace\src\testfolder";
int numberOfSubfolders;
//what is numberOfSubfolders in testfolder?
All help appreciated.
Upvotes: 4
Views: 11423
Reputation: 1
I just cringed so hard when I saw the for loop that has absolutely no use in the solution above. Just cut it out and do:
File dir = new File("yourDirPath");
File listDir[] = dir.listFiles();
int numberOfSubfolders = listDir.length;
This not only cuts the code in half, but the number of iterations is greatly reduced as you will run the for loop more as the number of directories increases. This only runs once.
Upvotes: -1
Reputation: 13749
You can use FileFilter
to list only directories:
File file = new File("/tmp");
File[] files = file.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory();
}
});
System.out.println("Folders count: " + files.length);
Java File
class is an example of the Composite Design Pattern, so you have to actually ask the instance if it's a file: isFile()
or if it's a directory isDirectory()
.
If you want to count directories, and you're using Java 8. Files.find
function, can do the same thing in a more concise manner (practically one-liner):
long count = Files.find(
Paths.get("/tmp"),
1, // how deep do we want to descend
(path, attributes) -> attributes.isDirectory()
).count() - 1; // '-1' because '/tmp' is also counted in
Upvotes: 14
Reputation: 68715
Try this:
File dir = new File("yourDirPath");
int numberOfSubfolders;
File listDir[] = dir.listFiles();
for (int i = 0; i < listDir.length; i++) {
if (listDir[i].isDirectory()) {
numberOfSubfolders++;
}
}
System.out.println("No of dir " + numberOfSubfolders);
Upvotes: 2
Reputation: 24885
Use the File
class, you can list the files that are inside it (if it is a folder/directory) and you can filter by the property that you want (isDirectory()
)
Then count the results.
Upvotes: 3