如何按升序排列的文件名进行排序? [英] How to sort file names in ascending order?

查看:185
本文介绍了如何按升序排列的文件名进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹中的一组文件,以及所有的人都开始用一个相似的名字,只有一个除外。下面是一个例子:

  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文件。任何人都可以帮忙吗?这里是code:

 进口java.io. *;
进口java.util.Arrays中;
进口了java.util.Comparator;
进口java.util.Scanner中;    公共类的FileInput {        公共无效userInput()
        {
            扫描仪扫描=新的扫描仪(System.in);
            的System.out.println(输入文件路径:);
            串dirPath = scanner.nextLine(); //注意到作为用户输入的目录路径            文件夹=新的文件(dirPath);
            如果(folder.isDirectory())
            {
                文件[] =的fileList folder.listFiles();                Arrays.sort(的fileList);                的System.out.println(目录项目present的\\ n总计数:+ fileList.length);
                //仅列出文件,因为我们已经申请文件过滤器
                对于(文件文件:的fileList)
                {
                    的System.out.println(file.getName());
                }                //创建一个过滤器,只返回文件。
                的FileFilter的FileFilter =新的FileFilter()
                {
                    @覆盖
                    公共布尔接受(档案文件){
                        返回file.isDirectory()!;
                    }
                };                的fileList = folder.listFiles(的FileFilter);                //按名称排序文件
                Arrays.sort(的fileList,新的比较()
                {
                    @覆盖
                    公众诠释比较(对象F1,F2对象){
                        返回((文件)F1).getName()的compareTo(((文件)F2).getName());
                    }
                });                //打印文件名升序排列文件
                对于(文件文件:的fileList)
                {
                    的System.out.println(file.getName());
                }            }
        }
    }


解决方案

你所要求的是数值排序。你需要实现一个比较并把它传递给在<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28T%5B%5D,%20java.util.Comparator%29\"相对=nofollow>数组排序#方法。在比较的方法,你需要提取从每个数字文件名的,然后比较这些数字。

为什么你现在所得到的输出的原因是,偏偏排序<一个href=\"http://stackoverflow.com/questions/5167928/what-is-natural-ordering-when-we-talk-about-sorting\">alphanumerically

下面一个是做的一个非常基本的方式。这code使用简单的字符串 -operation提取号码。这工作,如果你知道文件名的格式,你的情况 Spectrum_&LT;&号GT;的.txt 。做提取的一种更好的方法是使用定期EX pression

 公共类FileNameNumericSort {    私人最终静态文件[] =文件{
        新的文件(Spectrum_1.txt),
        新的文件(Spectrum_14.txt),
        新的文件(Spectrum_2.txt),
        新的文件(Spectrum_7.txt),
        新的文件(Spectrum_1000.txt),
        新的文件(Spectrum_999.txt),
        新的文件(Spectrum_9990.txt),
        新的文件(Spectrum_9991.txt),
    };    @测试
    公共无效sortByNumber(){
        Arrays.sort(文件,新的比较&LT;文件&gt;(){
            @覆盖
            公众诠释比较(文件O1,O2文件){
                INT N1 = extractNumber(o1.getName());
                INT N2 = extractNumber(o2.getName());
                返回N1 - N2;
            }            私人诠释extractNumber(字符串名称){
                INT I = 0;
                尝试{
                    INT S = name.indexOf('_')+ 1;
                    INT E = name.lastIndexOf('。');
                    串号= name.substring(S,E);
                    I =的Integer.parseInt(数);
                }赶上(例外五){
                    I = 0; //如果文件名不匹配的格式
                           //然后默认为0
                }
                返回我;
            }
        });        对于(F文件:文件){
            的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

I have a set of files in a folder, and all of them starting with a similar name, except one. Here is an example:

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

I am able to list all the files from the specified folder, but the list is not in an ascending order of the spectrum number. Example: I get the following result when the program is executed:

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

But this order is not correct. There should be Spectrum_1000.txt file after Spectrum_999.txt. Can anyone help? Here is the code:

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());
                }

            }   
        }
    }

解决方案

What you are asking for is numerical sort. You need implement a Comparator and pass it to the Arrays#sort method. In the compare method you need to extract the number from each filename an then compare the numbers.

The reason why you get the output you are getting now is that sorting happens alphanumerically

Here a is a very basic way of doing it. This code uses simple String-operation to extract the numbers. This works if you know the format of the filename, in your case Spectrum_<number>.txt. A better way of doing the extraction is to use 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());
        }
    }
}

Output

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

这篇关于如何按升序排列的文件名进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆