Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.list() returns files in a different order for 4.0 than 2.2

If i am using Android 2.2 and call File.list() method in BookGenerator.java, then pages and chapters come in exact sequence, but whenever I execute on Android 4.0 it gives me reverse pages list or reverse pages order.

Is there a compatibility issue between 2.2 and 4.0?

like image 937
Rizvan Avatar asked Feb 20 '23 14:02

Rizvan


2 Answers

You shouldn't rely on listFiles() for an ordered list of the pages:

http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#listFiles()

"There is no guarantee that the name strings in the resulting array will appear in any specific order;"

You have to create your own ordering system, based on file name or lastModified or file's size. You can either use a Comparator < File > or Comparator < String > for sorting the files in a SortedSet, or as mentionned earlier, create an own class for the items to sort that implements Comparable. I would suggest the first solution as it's a bit stupid to wrap the File or String class into an other one just for this functionality.

An example with a lot of memory overhead:

TreeSet<File> pages = new TreeSet<File>(new Comparator<File>(){
   public int compare(File first, File second) {
      return first.getName().compareTo(second.getName());
   }
});

for (File file : allFiles) {
   pages.add(file());
}

allFiles = pages.toArray();

If you want a more efficient one, you have to implement your own method for sorting an array in its place.

like image 159
Andras Balázs Lajtha Avatar answered Feb 23 '23 02:02

Andras Balázs Lajtha


The list() method does not guarantee any specific order for the items. The Android documentation lacks this point but the official Java SE API javadoc warns about it:

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.

You should sort the array with Collections.sort() before using it.

File fChapters = new File(internalStorage + bookName + "/Chapters");
// Obtain the chapters file names list (the files in the directory)
chapters = fChapters.list();
// Sort the file names according to default alphabetic ordering
Collections.sort(chapters)
// The chapters list is now sorted from A to Z

With the sort(List list, Comparator c) overload of this method you can define whatever order you need. For example, ignore the case of the letters in the titles:

Collections.sort(chapters, new Comparator<String>() {
    @Override
    public int compare(String chapter1, String chapter2) {
        return chapter1.compareToIgnoreCase(chapter2);
    }
});
like image 24
allprog Avatar answered Feb 23 '23 03:02

allprog