簡體   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