How to know the number of files in a folder using Java?

Asked

Viewed 840 times

1

In short, given a path that is a system folder, the return is the amount of files directly in the root of the folder (should not take into account files in subfolders). This would be used in a for iteration to access the files to make a "parsing" (recognize some information).

2 answers

3

Create an instance of the File class containing the path to which you want to get the total number of files.

File pasta = new File("/caminho/do/diretorio");

Now just create an array with the files using the method listFiles() Then we iterated over this array counting the number of files, without further delay would look like this:

int contador = 0;
File pasta = new File("/caminho/do/diretorio");
File[] lista = pasta.listFiles();

for (File file : lista) {
    if (file.isFile()) {
        contador ++;
    }
}

This way you don’t count the folders in the directory, in case you want to find out the total number of files counting the folders, just do lista.length

Att.

2


You can use the interface FileFilter for that reason:

File f = new File("/home/user/pasta");

File[] files = f.listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        return pathname.isFile();
    }
});

System.out.println(files.length);

The method accept of inteface FileFilter is called for each file of the folder in question. In the case on screen is made a test if the item is a file (isFile()), if, returns true and the file enters the vector that will be returned.

In Java 8 you could get Lambda:

File file = new File("/home/user/pasta");

Arrays.stream(file.listFiles())
        .filter(f -> f.isFile())
        .forEach(f -> System.out.println(f.getAbsolutePath()));

Where is being executed the System.out.println(f.getAbsolutePath()) you could call the file parser routine.

To count the files do it:

long quantidade = Arrays.stream(file.listFiles())
        .filter(f -> f.isFile())
        .count();
  • This solution is very interesting, it eliminates the need to create a loop only to contain the files. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.