I recently had a situation where I needed an ordered list of file names by newest to oldest so I thought I would share the code. This uses the last modified date as in my case that worked and as java.io doesn’t provide the created date only last modified.
First a method which returns an ArrayList of all files within a given directory.
public static ArrayList listFiles(String directoryName) { File directory = new File(directoryName); ArrayList filenames = new ArrayList(); // get all the files from a directory File[] fList = directory.listFiles(); if (fList != null) { for (File file : fList) { if (file.isFile()) { filenames.add(file.getAbsolutePath()); } else if (file.isDirectory()) { filenames.addAll(listFiles(file.getAbsolutePath())); } } } return filenames; }
We will then call the above method when building the ordered list of files. As below;
public static Map<String, Long> orderedListOfFiles(String directoryName) { Map<String, Long> fileMap = new HashMap<String, Long>(); // get all the files from a directory ArrayList filePaths = listFiles(directoryName); for (String path: filePaths) { File file = new File(path); fileMap.put(path, file.lastModified()); } List<Map.Entry<String, Long>> list = new LinkedList<Map.Entry<String, Long>>(fileMap.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Long>>() { public int compare(Map.Entry<String, Long> m1, Map.Entry<String, Long> m2) { if (m1.getValue() > m2.getValue()) return -1; return 1; } }); Map<String, Long> result = new LinkedHashMap<String, Long>(); for (Map.Entry<String, Long> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; }
To switch oldest to newest simply modify the compare method implemented inside the Comparator class.