Get the number of files in a folder, omitting subfolders

橙三吉。 提交于 2019-12-11 12:16:08

问题


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:

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!!


回答1:


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();
  }
}



回答2:


You will need to use the File class. Here is an example.




回答3:


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/



来源:https://stackoverflow.com/questions/4218422/get-the-number-of-files-in-a-folder-omitting-subfolders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!