Java 1.4 Sort Files - Recent & Latest

89 Views Asked by At

I'm having Java 1.4 version and need to sort the files by last modified. Sometimes I need to do it by recent and sometimes do it by oldest. I am not sure since Java 1.4 older version can be used in that project

File directory = new File("c:\\books\\");
File[] files = directory.listFiles();
1

There are 1 best solutions below

5
Ashish Patil On BEST ANSWER

For java 1.2 or higher:

    File directory = new File("c:\\books\\");
    File[] files = directory.listFiles();
    Arrays.sort(files, new Comparator() {
        public int compare(Object o1, Object o2) {
            File a1=(File)o1;
            File a2=(File)o2;
            if (a1.lastModified() < a2.lastModified())
                return -1;
            else if (a1.lastModified() > a2.lastModified())
                return 1;
            else
                return 0;
        }
    });