文件夹目录中子文件夹的数量 [英] Number of subfolders in a folder directory
问题描述
我有一个包含数据文件( .txt
等)和子文件夹的文件夹。
I have a folder which consists of both datafiles (.txt
etc) and subfolders.
在Java中,我该如何完成获取任何指定目录路径中子文件夹的数量的操作?
In Java, how would I accomplish getting the number of subfolders in any specified directory path?
(因此不包括数据文件;仅对子文件夹进行计数)
(so excluding the datafiles; only counting the subfolders)
我已经读过有关计算 .txt
文件数量的信息,但似乎找不到关于仅计算子文件夹的信息。
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?
感谢所有帮助。
推荐答案
您可以使用 FileFilter
仅列出目录:
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
类是综合设计模式,因此您必须实际询问实例是否是文件: isFile()
或如果它是目录 isDirectory()
。
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()
.
如果您要计数目录,并且正在使用Java8。 Files.find
函数,可以以更简洁的方式(实际上是单行)执行相同的操作:
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
这篇关于文件夹目录中子文件夹的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!