Benben
Benben

Reputation: 1455

In which order are the files in a directory read in by default by Java listFiles()?

I made the following program, which reads all files in the directory. All file names are composed of numbers (e.g. 10023134.txt).

File dir = new File(directoryPath);
File[] files = dir.listFiles();
for (File file : files)
    try {
        if ( !file.exists())
            continue;
        else if (file.isFile()) {
            // some process
        }
    } catch (Exception e) {}

I would like to know in what order the files in the directory are read by default.

It seems the program read the files by neither numerical order nor order of creation date.

Upvotes: 4

Views: 1728

Answers (4)

Bryan Xu
Bryan Xu

Reputation: 1

The order is filesystem dependent actually. Let's take Java 8 and Linux as an example. The implementations of listFiles() actually calls a native method java.io.FileSystem#list internally. Looking at the implementation of jdk\src\solaris\native\java\io\UnixFileSystem_md.c, we find out it calls the POSIX readdir64_r which is a variant of readdir. From https://utcc.utoronto.ca/%7Ecks/space/blog/unix/ReaddirOrder, we can know the order is actually traversal order of the underlying filesystem.

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97162

As specified in the JavaDoc:

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

If you want them sorted, you'll have to sort them yourself.

Note that if you sort using the default ordering, you'll still get different results depending on your OS. Again from the JavaDoc:

The ordering defined by this method depends upon the underlying system. On UNIX systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows systems it is not.

Upvotes: 7

MadProgrammer
MadProgrammer

Reputation: 347284

The order of the files is likely by OS default (or listing neutral) order and will depend on the how the OS returns a list of files back to Java.

There is no guarantee of the order that the files may be returned in.

You could use Arrays.sort(T[] Comparator<? super T> c) to sort the list after you have read it.

Upvotes: 6

elou
elou

Reputation: 1282

The files are sorted in the natural order of your operating system. It may be the creation order. If you want the list to be sorted, you can call

File[] files = Arrays.sort(dir.listFiles())

For another sort order, feel free to use your own Comparator. Regards.

Upvotes: 3

Related Questions