Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java File sorting order in windows and linux difference

I have a folder in windows/Linux which has below files

test_1a.play
test_1AA.play
test_1aaa.play
test-_1AAAA.play

I am reading files and and storing it But windows and linux gives different order. As my application runs in both platform I need consistent order(Linux order). Any suggestion for fixing this.

File root = new File( path );
File[] list = root.listFiles();
list<File> listofFiles = new ArrayList<File>();
.....
for ( File f : list ) {


...
read and store file in listofFiles
...
}
Collections.sort(listofFiles);

Windows gives me below order

test-_1AAAA.play
test_1a.play
test_1AA.play
test_1aaa.play

Linux gives me below order

test-_1AAAA.play
test_1AA.play
test_1a.play
test_1aaa.play
like image 502
vrbilgi Avatar asked May 28 '12 10:05

vrbilgi


1 Answers

You will need to implement your own Comparator<File> since the File.compareTo uses the "systems" order.

I think (not checked) that Linux uses the "standard" order by file name (case sensitive) so an example implementation could look like this:

public static void main(String[] args) {
    List<File> files = new ArrayList<File>();
    files.add(new File("test_1a.play"));
    files.add(new File("test_1AA.play"));
    files.add(new File("test_1aaa.play"));
    files.add(new File("test-_1AAAA.play"));

    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            String p1 = o1.getAbsolutePath();
            String p2 = o2.getAbsolutePath();
            return p1.compareTo(p2);
        }
    });

    System.out.println(files);
}

Outputs:

[test-_1AAAA.play, test_1AA.play, test_1a.play, test_1aaa.play]
like image 133
dacwe Avatar answered Sep 28 '22 12:09

dacwe