javafiledirectory

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:

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


Solution

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