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
– user28595