sorting files based on its creation date in android

    List<File> fileList = new ArrayList<File>();
    Collections.sort(fileList, new Comparator<File>() {

        @Override
        public int compare(File file1, File file2) {
            long k = file1.lastModified() - file2.lastModified();
            if(k > 0){
               return 1;
            }else if(k == 0){
               return 0;
            }else{
              return -1;
           }
        }
    });

I want list of file based on my creation date.

As the two previous answers pointed out, you can sort the files according to the modification date:

file.lastModified()

But the modification date is updated e.g. in the instant of renaming a file. So, this won't work to represent the creation date.

Unfortunately, the creation date is not available, thus you need to rethink your basic strategy:

see an old answer of CommonsWare


try this may help you,

public static void main(String[] args) throws IOException {
    File directory = new File(".");
    // get just files, not directories
    File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);

    System.out.println("Default order");
    displayFiles(files);

    Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
    System.out.println("\nLast Modified Ascending Order (LASTMODIFIED_COMPARATOR)");
    displayFiles(files);

    Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
    System.out.println("\nLast Modified Descending Order (LASTMODIFIED_REVERSE)");
    displayFiles(files);

}

public static void displayFiles(File[] files) {
    for (File file : files) {
        System.out.printf("File: %-20s Last Modified:" + new Date(file.lastModified()) + "\n", file.getName());
    }
}

Tags:

File

Android