如何在java中使用不同的位数排序? [英] how to sort with different number of digits in java?

查看:168
本文介绍了如何在java中使用不同的位数排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用f.listFiles()在目录中创建了一个文件列表。

不幸的是,它们的命名方式如下:

001.pdf

098.pdf

100.pdf

1000.pdf

现在目录中的文件数组在100.pdf之前设置了1000.pdf。

我如何对这个文件进行排序以使文件以正确的顺序返回?

I created a list of files in a directory with f.listFiles().
Unfortunately they are very differently named like:
001.pdf
098.pdf
100.pdf
1000.pdf
now the array of files in the directory sets the 1000.pdf before the 100.pdf.
How can I sort this so that the files areback in the right order?

感谢您的帮助!

推荐答案

您可以在空格前添加相同长度的名称:

You may prepend the names with spaces to the same length:

File[] files = f.listFiles();
if(files != null) {
    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return String.format("%100s", o1.getName()).compareTo(
                   String.format("%100s", o2.getName()));
        }
    });
    System.out.println(Arrays.toString(files));
}

如果您使用的是Java-8则更短:

Or shorter if you are using Java-8:

File[] files = f.listFiles();
if(files != null) {
    Arrays.sort(files, Comparator.comparing(file -> String.format("%100s", file.getName())));
    System.out.println(Arrays.toString(files));
}

这篇关于如何在java中使用不同的位数排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆