0

I have some files in a folder stored in Android device.

Folder name = english/

File names = 001-001-0000.png, 001-001-000.png, 001-001-001.png, 001-001,002.png, 001-001-003.png ... upto 001-001-010.png

I have to load them on screen in sorted order by their name. I am using this code

String[] files = dir.list();
    Arrays.sort(files, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2);
        }
    });

The result I got is

001-001-000.png 001-001-0000.png 001-001-001.png 001-001,002.png 001-001-003.png ... 001-001-010.png

But when I check on explorer on my Windows PC I got

001-001-0000.png 001-001-000.png 001-001-001.png 001-001,002.png 001-001-003.png ... 001-001-010.png

The difference here is that the file which ends with four 0s (001-001-0000.png) comes before the file which ends with three 0s (001-001-000.png) and I need the same sorting order in my code.

Karan Nagpal
  • 521
  • 1
  • 8
  • 19

2 Answers2

1

Try this compare method:

@Override
public int compare(String o1, String o2) {
    String o1_prefix = o1.split(".")[0];
    String o2_prefix = o2.split(".")[0];
    if(o1_prefix.startsWith(o2_prefix)) 
        return -1;
    else if(o2_prefix.startsWith(o1_prefix)) 
        return 1;
    else return o1.compareToIgnoreCase(o2);
}
Susmit Agrawal
  • 3,649
  • 2
  • 13
  • 29
0

The reason why Windows is sorting it like that is, because Windows uses "numerical sorting" since Windows 7. That means Windows sorts your files numerically by increasing number value. if you dont want Windows to sort in this numerical order, you can turn this function off.

My source: http://www.alliancegroup.co.uk/windows7-explorer-sort-order.htm

Donatic
  • 323
  • 1
  • 13