view raw
vrbilgi vrbilgi - 7 months ago 23
Java Question

java File sorting order in windows and linux difference

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

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

Windows gives me below order

Linux gives me below order


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(""));
    files.add(new File(""));
    files.add(new File(""));
    files.add(new File(""));

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