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

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 (you should not consider files in subfolders). This would be used in an iteration with for to access the files to do a "parse" (recognize some information).

    
asked by anonymous 16.10.2016 / 05:29

2 answers

2

You can use the FileFilter interface for this:

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 accept method of inteface FileFilter is called for each file in the folder in question. In the case on screen a test is done if the item is a file ( isFile() ), if it returns true and the file enters the vector that will be returned.

In Java 8 you could lay claim to 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 running System.out.println(f.getAbsolutePath()) you could call the routine that does the parser of the file.

To tell the files do this:

long quantidade = Arrays.stream(file.listFiles())
        .filter(f -> f.isFile())
        .count();
    
16.10.2016 / 16:19
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() After iterating over this array counting the number of files, without further ado it 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 do not count directory folders, if you want to find out the total number of files counting folders, just do lista.length

Att.

    
16.10.2016 / 05:53