• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting Files By Timestamp  RSS feed

 
Chris Rosenquest
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Does anyone have an example where I can use java.io.File.lastModified() to sort the files in a directory?

I'm processing a list of files from a directory and they need to be processed in order of lastModified millis.

TIA,
Chris Rosenquest
 
Mikie Williams
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try something like this. I hope this helps.

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

public class SortFiles {

public static void main(String[] args) {
File mainDir = new File("src");
File[] files = mainDir.listFiles();
Comparator fileComparator = new Comparator() {

public int compare(Object o1, Object o2) {
File file1 = (File) o1;
File file2 = (File) o2;

return (int) (file1.lastModified() - file2.lastModified());
}

};

Arrays.sort(files, fileComparator);

for (int i = 0; i < files.length; i++) {
System.out.println("File: " + files[i].getName()
+ " last modified: " + new Date(files[i].lastModified()));
}
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!