• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Sorting Files By Timestamp

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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()));
}
}
 
bacon. tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic