I have some sort of batch program that should pick up a file from a directory and process it.
Since this program is supposed to:
...what is the best way to only pick one file from the directory - without using File.list()
(might be hundreds of files)?
In Java 7 you could use a DirectoryStream, but in Java 5, the only ways to get directory entries are list()
and listFiles()
.
Note that listing a directory with hundreds of files is not ideal but still probably no big deal compared to processing one of the files. But it would probably start to be problematic once the directory contains many thousands of files.
Use a FileFilter
(or FilenameFilter
) written to accept only once, for example:
File dir = new File("/some/dir");
File[] files = dir.listFiles(new FileFilter() {
boolean first = true;
public boolean accept(final File pathname) {
if (first) {
first = false;
return true;
}
return false;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With