Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java File.list() consistent order?

Tags:

java

This is an awful question (in my mind) and I've tried my best to find myself useful documentation with little luck - anyway, here goes:

I have code which needs to do some operation on all files in a directory. I set up the directory in a File object and use fileObject.list() to iterate over the files in the directory. I left this code running overnight and it (after much chugging) crashed at some point. I'm trying to figure out at what point this happened (yes I had awful logging). Now, according to this javadoc there is no guarantee of an order (alphabetical or otherwise) when listing files, I'm wondering if there is any guarantee of consistency? Meaning when I run the same code twice, would I get the exact same order of files? Logic tells me it should and I've resumed operations based on that but I'm suspicious of this. Also, I'm curious on what 'no specific order means' from the javadoc.

like image 884
kyun Avatar asked Jun 30 '11 18:06

kyun


1 Answers

That language means you should not rely on any property of the order including consistency from run to run.

If there is a linked list of files in some in-memory data structure, a driver might move the most recently accessed to the front of the list to optimize for repeated file access. This might change the order in which files are listed even though no file has been modified.

If you want a consistent order, you can do something like

Arrays.sort(
   myFileArray,
   new Comparator<File>() {
     public int compare(File a, File b) {
       return a.getName().compareTo(b.getName());
     }
   });
like image 130
Mike Samuel Avatar answered Nov 15 '22 05:11

Mike Samuel