1public class ExampleSortFilesByDate {
2 public static void main(String[] args) {
3 File dir = new File("d:\\test");
4 File[] files = dir.listFiles();
5 System.out.println("-- printing files before sort --");
6 printFiles(files);
7 sortFilesByDateCreated(files);
8 System.out.println("-- printing files after sort --");
9 printFiles(files);
10 }
11
12 private static void printFiles(File[] files) {
13 for (File file : files) {
14 long m = getFileCreationEpoch(file);
15 Instant instant = Instant.ofEpochMilli(m);
16 LocalDateTime date = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
17 System.out.println(date+" - "+file.getName());
18 }
19 }
20
21 public static void sortFilesByDateCreated (File[] files) {
22 Arrays.sort(files, new Comparator<File>() {
23 public int compare (File f1, File f2) {
24 long l1 = getFileCreationEpoch(f1);
25 long l2 = getFileCreationEpoch(f2);
26 return Long.valueOf(l1).compareTo(l2);
27 }
28 });
29 }
30
31 public static long getFileCreationEpoch (File file) {
32 try {
33 BasicFileAttributes attr = Files.readAttributes(file.toPath(),
34 BasicFileAttributes.class);
35 return attr.creationTime()
36 .toInstant().toEpochMilli();
37 } catch (IOException e) {
38 throw new RuntimeException(file.getAbsolutePath(), e);
39 }
40 }
41}