获取文件夹中的文件数,省略子文件夹 [英] Get the number of files in a folder, omitting subfolders
问题描述
是否可以使用Java获取文件夹中文件的数量?
我的问题也许看起来很简单,但是我是Java领域的新手!
Is the any way to get the number of files in a folder using Java? My question maybe looks simple, but I am new to this area in Java!
更新:
我在评论中看到了链接。他们没有解释要忽略目标文件夹中的子文件夹。
该怎么做?如何忽略子文件夹并获取指定目录中的文件?
I saw the link in the comment. They didn't explained to omit the subfolders in the target folder. How to do that? How to omit sub folders and get files in a specified directory?
任何建议!
推荐答案
使用纯Java的一种方法是:
One approach with pure Java would be:
int nFiles = new File(filename).listFiles().length;
编辑(问题编辑后):
您可以排除带有listFiles()变体且接受FileFilter的文件夹。 FileFilter接受一个文件。您可以测试文件是否是目录,如果是,则返回false。
You can exclude folders with a variant of listFiles() that accepts a FileFilter. The FileFilter accepts a File. You can test whether the file is a directory, and return false if it is.
int nFiles = new File(filename).listFiles( new MyFileFilter() ).length;
...
private static class MyFileFilter extends FileFilter {
public boolean accept(File pathname) {
return ! pathname.isDirectory();
}
}
这篇关于获取文件夹中的文件数,省略子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!