Java按扩展名对文件名的String数组进行排序

标签 java arrays file sorting filenames

我有一个文件名数组,需要按文件名的扩展名对该数组进行排序。有没有简单的方法可以做到这一点?

最佳答案

Arrays.sort(filenames, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        // the +1 is to avoid including the '.' in the extension and to avoid exceptions
        // EDIT:
        // We first need to make sure that either both files or neither file
        // has an extension (otherwise we'll end up comparing the extension of one
        // to the start of the other, or else throwing an exception)
        final int s1Dot = s1.lastIndexOf('.');
        final int s2Dot = s2.lastIndexOf('.');
        if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
            s1 = s1.substring(s1Dot + 1);
            s2 = s2.substring(s2Dot + 1);
            return s1.compareTo(s2);
        } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
            return -1;
        } else { // only s1 has an extension, so s1 goes second
            return 1;
        }
    }
});

为了完整性:java.util.Arraysjava.util.Comparator .

关于Java按扩展名对文件名的String数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/440430/

相关文章:

java - 如何使用html、servlet将图像插入mysql

php - 数组文件 isset 错误返回 False

java - 在java游戏中隐藏分数文件

python - 在 python 中使用 numpy 进行列数学运算

c# - 加密文件并将其发送通过

file - 我如何要求和提供Clojure文件?

Java基础 - 对方法中的返回类型和返回语句的一些混淆

java - 从 AWS 上的 SQS 队列连续轮询

java - 安卓图标电池

java - 从存储在 map 内的数组中获取值