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

If I use Android 2.2 and call the File.list() method in BookGenerator.java , then the pages and chapters come in the exact sequence, but every time I run on Android 4.0, it gives me a list of back pages or an order of back pages.

Is there a compatibility issue between 2.2 and 4.0?

+4
source share
3 answers

You should not rely on listFiles () for an ordered list of 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 be displayed in any particular order:"

You need to create your own ordering system based on the file name or lastModified or file size. You can use the Comparator <File> or Comparator <String> to sort files in a SortedSet, or, as mentioned earlier, create your own class for sorting elements that implements Comparable. I would suggest the first solution, since it's a little silly to wrap a File or String class in another for this function.

An example with a large amount 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 must implement your own method to sort the array in its place.

+5
source

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

There is no guarantee that name strings in the resulting array will appear in any particular order; they are not, in particular, guaranteed to appear in alphabetical order.

Before use, sort the Collections.sort() array.

 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, pay attention to the case of letters in the headings:

 Collections.sort(chapters, new Comparator<String>() { @Override public int compare(String chapter1, String chapter2) { return chapter1.compareToIgnoreCase(chapter2); } }); 
+3
source

Use Comparable to sort it yourself.

0
source

Source: https://habr.com/ru/post/1411053/


All Articles