(Java)文件名末尾带有数字的数组未按数字顺序排序

问题描述 投票:0回答:1

我正在尝试创建一个数组,将文件夹中的所有文件放入数组中。文件名末尾都有一个数字来指示帧顺序,但我的代码似乎没有正确排序。

import java.util.Scanner;
import java.io.File;
import java.util.Arrays;


public class OsuSkinFramerDriver {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        int numFrames = 0;
        int frames;
        String assetType;

        System.out.println();
        System.out.println("What kind of asset is this (example: menu-back) (Please make sure you add any special characters(dashes) or else it wont work");
        assetType = keyboard.nextLine();
        System.out.println();
        System.out.println("Make sure you have all of the images you want to rename in a folder. When you do, input anything");
        keyboard.nextLine();

        File directory = new File("C:\\Users\\chris\\IdeaProjects\\Osu Skin framer\\src\\TEst");
        frames = directory.list().length;
        System.out.println();
        System.out.println("File Count:" + frames);

        String contents[] = directory.list();

        Arrays.sort(contents);

        for(int i=0; i < contents.length; i++) {
            System.out.println(contents[i]);
        }


        while(numFrames <= frames){

                File image = new File("C:\\Users\\chris\\IdeaProjects\\Osu Skin framer\\src\\TEst\\" + contents[numFrames]);

                File rename = new File("C:\\Users\\chris\\IdeaProjects\\Osu Skin framer\\src\\TEst\\" + assetType + "-" + numFrames);

                image.renameTo(rename);

                numFrames++;
            }
    }
}

我正在尝试使用 Arrays.sort() 方法,但是当我尝试对数组进行排序时,我得到如下结果

1
10
100
101
...

与结果相反

1
2
3
4
...

如何按数字顺序对数组进行排序?

java arrays sorting
1个回答
0
投票

您当前的数组是

String
类型,因此
Arrays.sort()
操作将按字典顺序对数组进行排序,作为 text,而不是整数。要按数字排序,请使用:

Arrays.sort(contents, Comparator.comparingInt(Integer::valueOf));
© www.soinside.com 2019 - 2024. All rights reserved.