Get the number of files in a folder, omitting subf

2019-08-15 05:26发布

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

3条回答
不美不萌又怎样
2楼-- · 2019-08-15 06:11

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();
  }
}
查看更多
放我归山
3楼-- · 2019-08-15 06:11

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/

查看更多
在下西门庆
4楼-- · 2019-08-15 06:31

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

查看更多
登录 后发表回答