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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With