Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-io

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.

like image 524
Benben Avatar asked Sep 16 '25 06:09

Benben


2 Answers

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.

like image 183
Robby Cornelissen Avatar answered Sep 17 '25 20:09

Robby Cornelissen


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.

like image 34
MadProgrammer Avatar answered Sep 17 '25 21:09

MadProgrammer