繁体   English   中英

排序元素 File[] 数组

[英]sorting elements File[] array

我正在尝试对fList数组中的文件名进行排序。 最初fList是这样排序的https://i.stack.imgur.com/OCqJR.jpg和结果https://i.stack.imgur.com/GGBsq.jpg

我希望结果按照文件名之前的数字排序,如下所示:

    1. 硒介绍
    1. java和Selenium学习的完整安装指南
    1. 为 Selenium 自动化复习 Java 概念
    1. 手动测试人员和初学者的 CORE JAVA 深入

...

    1. 奖金!! 学生特辑

我有something()方法可以从fList[x]文件名中获取数字,以便稍后在执行swap(fList[x], fList[y])时进行比较swap(fList[x], fList[y])正如您从输出控制台所看到的那样。 我不确定我是否理解File[]实际上是如何存储和更改其元素的

public static void main(String[] args) {

        File file = new File("pathToFolder");
        File[] fList = file.listFiles();
        for(int x = 0; x < fList.length; x++) {
            int numberX = something(fList[x]);
            for(int y = x; y < fList.length; y++) {
                int numberY = something(fList[y]);
                if(numberX > numberY) {
                    File temp = fList[x];
                    fList[x] = fList[y];
                    fList[y] = temp;
                }
            }
        }
        for(int x = 0; x < fList.length; x++) {         
            System.out.println(fList[x].getName());
        }

    }

    static int something(File file) {
        String temp = file.getName();
        String number = "";
        for(int st = 0; st < temp.length(); st++) {
            if(temp.charAt(st) == '.') break;
            number += temp.charAt(st);
        }
        int fileNumber = Integer.parseInt(number); 
        return fileNumber;
    }

如果您使用的是Java8试试这个,您当然可以调整它以满足您的要求:

List<File> sortedFiles = stream(requireNonNull(file.listFiles()))
            .sorted(File::compareTo)
            .collect(toList());

您还可以使用类Arrays提供的sort方法:

File[] sortedFiles = file.listFiles();
    // One liner
    Arrays.sort(sortedFiles);

这两种解决方案都依赖于File类中compareTo的实现。 官方文档的链接

我在我的个人git repo 中添加了一个测试

下面的代码怎么样:

public static void main(String[] args) {
    File file = new File("pathToFolder");
    File[] fList = file.listFiles();
    Map<Integer, File> fileMap = new TreeMap<Integer, File>();
    for (int x = 0; x < fList.length; x++) {
        int numberX = something(fList[x]);
        fileMap.put(numberX, fList[x]);
    }

    fileMap.forEach((k, v) -> System.out.println((v.getName())));

}

static int something(File file) {
    String temp = file.getName();
    String number = temp.split("\\.")[0];
    int fileNumber = Integer.parseInt(number);
    return fileNumber;
}

暂无
暂无

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

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