java - 如何按升序对文件名进行排序?

标签 java file sorting arraylist

我在一个文件夹中有一组文件,所有文件都以相似的名称开头,除了一个。这是一个例子:

Coordinate.txt
Spectrum_1.txt
Spectrum_2.txt
Spectrum_3.txt
.
.
.
Spectrum_11235

我能够列出指定文件夹中的所有文件,但该列表不是按谱图编号的升序排列。示例:我在执行程序时得到以下结果:

Spectrum_999.txt
Spectrum_9990.txt
Spectrum_9991.txt
Spectrum_9992.txt
Spectrum_9993.txt
Spectrum_9994.txt
Spectrum_9995.txt
Spectrum_9996.txt
Spectrum_9997.txt
Spectrum_9998.txt
Spectrum_9999.txt

但是这个顺序是不正确的。 Spectrum_999.txt 之后应该有Spectrum_1000.txt 文件。谁能帮忙?这是代码:

import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

    public class FileInput {

        public void userInput()
        {
            Scanner scanner = new Scanner( System.in );
            System.out.println("Enter the file path: ");
            String dirPath = scanner.nextLine(); // Takes the directory path as the user input

            File folder = new File(dirPath);
            if(folder.isDirectory())
            {
                File[] fileList = folder.listFiles();

                Arrays.sort(fileList);

                System.out.println("\nTotal number of items present in the directory: " + fileList.length );


                // Lists only files since we have applied file filter
                for(File file:fileList)
                {
                    System.out.println(file.getName());
                }

                // Creating a filter to return only files.
                FileFilter fileFilter = new FileFilter()
                {
                    @Override
                    public boolean accept(File file) {
                        return !file.isDirectory();
                    }
                };

                fileList = folder.listFiles(fileFilter);

                // Sort files by name
                Arrays.sort(fileList, new Comparator()
                {
                    @Override
                    public int compare(Object f1, Object f2) {
                        return ((File) f1).getName().compareTo(((File) f2).getName());
                    }
                });

                //Prints the files in file name ascending order
                for(File file:fileList)
                {
                    System.out.println(file.getName());
                }

            }   
        }
    }

最佳答案

您要求的是数字排序。你需要实现一个 Comparator并将其传递给 Arrays#sort方法。在比较方法中,您需要从每个文件名中提取数字,然后比较数字。

您得到现在得到的输出的原因是排序发生了 alphanumerically

这是一个非常基本的方法。此代码使用简单的 String - 提取数字的操作。如果您知道文件名的格式,这将起作用,在您的情况下为 Spectrum_<number>.txt .一种更好的提取方法是使用 regular expression .

public class FileNameNumericSort {

    private final static File[] files = {
        new File("Spectrum_1.txt"),
        new File("Spectrum_14.txt"),
        new File("Spectrum_2.txt"),
        new File("Spectrum_7.txt"),     
        new File("Spectrum_1000.txt"), 
        new File("Spectrum_999.txt"), 
        new File("Spectrum_9990.txt"), 
        new File("Spectrum_9991.txt"), 
    };

    @Test
    public void sortByNumber() {
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                int n1 = extractNumber(o1.getName());
                int n2 = extractNumber(o2.getName());
                return n1 - n2;
            }

            private int extractNumber(String name) {
                int i = 0;
                try {
                    int s = name.indexOf('_')+1;
                    int e = name.lastIndexOf('.');
                    String number = name.substring(s, e);
                    i = Integer.parseInt(number);
                } catch(Exception e) {
                    i = 0; // if filename does not match the format
                           // then default to 0
                }
                return i;
            }
        });

        for(File f : files) {
            System.out.println(f.getName());
        }
    }
}

输出

Spectrum_1.txt
Spectrum_2.txt
Spectrum_7.txt
Spectrum_14.txt
Spectrum_999.txt
Spectrum_1000.txt
Spectrum_9990.txt
Spectrum_9991.txt

关于java - 如何按升序对文件名进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16898029/

相关文章:

java - 实时过滤输入?

c# - 如何将文本文件存储到具有不同字符串格式的数组中?

php - 替代 MySQL 中的冒泡排序

C 程序不断返回 1

javascript - 基于虚线键父值从平面数组创建关联数组

java - 无法在从 XPage 调用的 java 中获取 openNTF session - 版本 10.0.1

java - 更改 JTable 的外观

java - 类文字语法是否必要?

python - 如何用 python "join"两个文本文件?

c - 不会从文件读取到结构