How do I count the number of files in a directory using Java ? For simplicity, lets assume that the directory doesn't have any sub-directories.
I know the standard method of :
new File(<directory path>).listFiles().length
But this will effectively go through all the files in the directory, which might take long if the number of files is large. Also, I don't care about the actual files in the directory unless their number is greater than some fixed large number (say 5000).
I am guessing, but doesn't the directory (or its i-node in case of Unix) store the number of files contained in it. If I could get that number straight away from the file system, it would be much faster. I need to do this check every time on a Tomcat server before the back-end starts doing the real processing for the http request. Therefore, speed is of paramount importance.
I could run a daemon every once in a while to clear the directory. I know that. So plz don't give me that solution.