Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through all the files in a folder (if the names of the files are unknown)? [duplicate]

Tags:

java

loops

There is a folder: C:\\Users\..myfolder

It contains .pdf files (or any other, say .csv). I cannot change the names of those files, and I do not know the number of those files. I need to loop all of the files one by one. How can I do this?

(I know how to do this if I knew the names)

like image 357
Buras Avatar asked Dec 11 '22 10:12

Buras


1 Answers

Just use File.listFiles

final File file = new File("whatever");
for(final File child : file.listFiles()) {
    //do stuff
}

You can use the FileNameExtensionFilter to filter your files too

final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "pdf", "csv"//, whatever other extensions you want);
final File file = new File("whatever");
for (final File child : file.listFiles()) {
    if(extensionFilter.accept(child)) {
        //do stuff
    }
}

Annoyingly FileNameExtensionFilter comes from the javax.swing package so cannot be used directly in the listFiles() api, it is still more convenient than implementing a file extension filter yourself.

like image 161
Boris the Spider Avatar answered Dec 28 '22 22:12

Boris the Spider