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;
    }
});
Share:
14,163
stephanos
Author by

stephanos

Updated on June 04, 2022

Comments

  • stephanos
    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
    Stephen C over 12 years
    Your 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
    stephanos over 12 years
    best answer, short and sweet :)
  • Alistair A. Israel
    Alistair A. Israel over 12 years
    True enough, but it does avoid the overhead of creating and returning an entire array of File or filename objects.
  • Gangnus
    Gangnus over 8 years
    DirectoryStream is the Interface, we cannot use it for any work, including getting a file.