Count number of files in a directory

The following static method returns a total number of files in a directory, including files in sub directories:

    /**
     * Counts total number of files in a directory, including sub directories
     * @param dir the directory
     * @return total number of files
     */
    public static int countFilesInDirectory(File dir) {
        int totalFiles = 0;

        File[] listFiles = dir.listFiles();
        if (listFiles != null && listFiles.length > 0) {
            for (File file : listFiles) {
                if (file.isFile()) {
                    totalFiles++;
                } else {
                    totalFiles += countFilesInDirectory(file);
                }
            }
        }

        return totalFiles;
    }
Be Sociable, Share!

2 thoughts on “Count number of files in a directory

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <font color="" face="" size=""> <span style="">