Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first file in directory with Java

Tags:

java

io

java-io

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)?

like image 663
stephanos Avatar asked Dec 28 '22 15:12

stephanos


2 Answers

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.

like image 153
Michael Borgwardt Avatar answered Dec 31 '22 15:12

Michael Borgwardt


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;
    }
});
like image 33
Alistair A. Israel Avatar answered Dec 31 '22 15:12

Alistair A. Israel