简体   繁体   English

java文件排序顺序与windows和linux的区别

[英]java File sorting order in windows and linux difference

I have a folder in windows/Linux which has below files 我在Windows / Linux中有一个文件夹,下面有文件

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. 我正在读取文件并存储它但是windows和linux给出了不同的顺序。 As my application runs in both platform I need consistent order(Linux order). 由于我的应用程序在两个平台上运行,我需要一致的顺序(Linux顺序)。 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 Windows给我下面的订单

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

Linux gives me below order Linux给了我以下订单

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

You will need to implement your own Comparator<File> since the File.compareTo uses the "systems" order. 您需要实现自己的Comparator<File>因为File.compareTo使用“systems”命令。

I think (not checked) that Linux uses the "standard" order by file name (case sensitive) so an example implementation could look like this: 我认为(未检查)Linux使用文件名的“标准”顺序(区分大小写),因此示例实现可能如下所示:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM