The difference between Java file sorting in Windows and Linux

The difference between Java file sorting in Windows and Linux … here is a solution to the problem.

The difference between Java file sorting in Windows and Linux

I have a folder in Windows/Linux with the following files

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

I’m reading the file and storing it, but Windows and Linux give a different order. Since my application runs on both platforms, I need a consistent order (Linux order). Any suggestions to resolve this issue.

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 the following command

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

Linux gives me the following command

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

Solution

You need to implement your own Comparator<File> from File.compareTo using the “System” command.

I think (unchecked) Linux uses the “standard” order of filenames (case sensitive), so the example implementation might 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);
}

Output:

[test-_1AAAA.play, test_1AA.play, test_1a.play, test_1aaa.play]

Related Problems and Solutions