Find first file in directory with Java
14,163
Solution 1
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.
Solution 2
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;
}
});
Author by
stephanos
Updated on June 04, 2022Comments
-
stephanos almost 2 years
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:
- run on JDK 5,
- be small (no external libraries)
- and fast! (with a bang)
...what is the best way to only pick one file from the directory - without using
File.list()
(might be hundreds of files)? -
Stephen C over 12 yearsYour point about big directories is very true. But these cause problems for lots of things apart from Java. The best approach is not to put huge numbers of files into a single directory.
-
stephanos over 12 yearsbest answer, short and sweet :)
-
Alistair A. Israel over 12 yearsTrue enough, but it does avoid the overhead of creating and returning an entire array of
File
or filename objects. -
Gangnus over 8 yearsDirectoryStream is the Interface, we cannot use it for any work, including getting a file.