javajava-io

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.


Solution

  • 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.