Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

java : Sort Files based on Creation Date

I am trying to read the latest 10 files based on their creation date .

I tried with this code , but it isn't working , i mean , it doesn't show the new file names in the output when ever i add new files .

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

public class Main {
    public static void main(String[] args) {
        File inboxDir = new File("D:\SPOTO");
        File[] files = inboxDir.listFiles();
        Arrays.sort( files, new Comparator()
        {
        public int compare(Object o1, Object o2) {
        return new Long(((File)o1).lastModified()).compareTo(new Long(((File) o2).lastModified()));
        }

        });


        for(int i=0;i<10;i++)
        {
            System.out.println(files[i].getName());
        }


    }
}

I even tried with apache commons io , but that isn't working either ( Means doesn't show new files when new files are created in that directory )

This is my Apache commons io version

import org.apache.commons.io.comparator.LastModifiedFileComparator;

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

public class Main {
    public static void main(String[] args) {
        File dir = new File("c:");
        File[] files = dir.listFiles();

        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(),
                    file.lastModified());
        }

        Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(),
                    file.lastModified());
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try flipping the comparison order:

return new Long(((File)o2).lastModified()).compareTo(new Long(((File) o1).lastModified()));

This works for me testing locally just now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...