Get the number of files in a folder, omitting subfolders
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!
Update:开发者_StackOverflow中文版
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?
Any suggestions!!
One approach with pure Java would be:
int nFiles = new File(filename).listFiles().length;
Edit (after question edit):
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();
}
}
You will need to use the File class. Here is an example.
This method allows you to count files inside the folder without loading all files into memory at once (which is good considering folders with big amount of files which could crash your program), and you can additionaly check file extension etc. if you put additional condition next to f.isFile().
import org.apache.commons.io.FileUtils;
private int countFilesInDir(File dir){
int cnt = 0;
if( dir.isDirectory() ){
Iterator it = FileUtils.iterateFiles(dir, null, false);
while(it.hasNext()){
File f = (File) it.next();
if (f.isFile()){ //this line weeds out other directories/folders
cnt++;
}
}
}
return cnt;
}
Here you can download commons-io library: https://commons.apache.org/proper/commons-io/
精彩评论