How to sort file names in ascending order?

前端 未结 9 2015
孤独总比滥情好
孤独总比滥情好 2020-12-05 10:30

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         


        
相关标签:
9条回答
  • 2020-12-05 11:10
    Arrays.sort(fileList, new Comparator()
    {
        @Override
        public int compare(Object f1, Object f2) {
            String fileName1 = ((File) f1).getName();
            String fileName2 = ((File) f1).getName();
    
            int fileId1 = Integer.parseInt(fileName1.split("_")[1]);
            int fileId2 = Integer.parseInt(fileName2.split("_")[1]);
    
            return fileId1 - fileId2;
        }
    });
    

    make sure to handle files that does not has _ in the name

    0 讨论(0)
  • 2020-12-05 11:12

    you can use Collections.sort(fileList); to sort arraylist.

    Then use

     for(File file:fileList)                
             System.out.println(file.getName());
    

    Collections.sort()

    0 讨论(0)
  • 2020-12-05 11:13

    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
    
    0 讨论(0)
  • 2020-12-05 11:13

    The NameFileComparator class available in Commons IO library that have feature for sorting file array by name,last modified date, size and many more.Files can be sorted in ascending and descending order, with case sensitivity or case insensitivity.

    Import :

    org.apache.commons.io.comparator.NameFileComparator

    Code :

    File directory = new File(".");
    File[] files = directory.listFiles();
    Arrays.sort(files, NameFileComparator.NAME_COMPARATOR)
    
    0 讨论(0)
  • Best implementation of a smart AlphaDecimal comparator by Ivan Gerasimiv was found here. It was proposed as an extension of a standard JDK Comparators here and discussed in a thread here.
    Unfortunately this change still didn't make its way into JDK (as far as I know). But you can use the code from the first link as a solution. For me it worked like a charm.

    0 讨论(0)
  • 2020-12-05 11:22

    Just use:

    1. For Ascending: Collections.sort(List)

    2. For Descending : Collections.sort(List,Collections.reverseOrder())

    0 讨论(0)
提交回复
热议问题