Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of files in a directory using Java

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 for every HTTP request on a Tomcat server before the back-end starts doing the real processing. Therefore, speed is of paramount importance.

I could run a daemon every once in a while to clear the directory. I know that, so please don't give me that solution.

like image 441
euphoria83 Avatar asked Mar 26 '09 20:03

euphoria83


People also ask

How do I count the number of files in a directory?

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1.

How do I count the number of files in multiple folders?

Browse to the folder containing the files you want to count. Highlight one of the files in that folder and press the keyboard shortcut Ctrl + A to highlight all files and folders in that folder. In the Explorer status bar, you'll see how many files and folders are highlighted, as shown in the picture below.

Which command is used to count the number of directories and files?

The ls command is the most basic command used by everyone in the Linux system. The below ls command will count the number of files and directories in the current directory.


1 Answers

Ah... the rationale for not having a straightforward method in Java to do that is file storage abstraction: some filesystems may not have the number of files in a directory readily available... that count may not even have any meaning at all (see for example distributed, P2P filesystems, fs that store file lists as a linked list, or database-backed filesystems...). So yes,

new File(<directory path>).list().length 

is probably your best bet.

like image 108
Varkhan Avatar answered Sep 22 '22 13:09

Varkhan