Sort an array of File objects by last modified date in Java

/**
 * Sorts an array of Files by the last modified date property; if the second
 * parameter is "desc", then sorting is done descending order, otherwise
 * it will be ascending. 
 * @param fList : An array of Java "File" objects, not sorted
 * @return File[] : An array of Java "File" objects, sorted by last modified date
 * @author C. Peter Chen http://dev-notes.com
 * @date 20080527
 */
public static File[] sortFilesByLastModDate(File[] fList, String order) {
	Arrays.sort(fList, new Comparator() {
		public int compare(File file1, File file2) {
			if ("desc".equals("order")) {
				return (int)(file2.lastModified() - file1.lastModified());
			}
			else {
				return (int)(file1.lastModified() - file2.lastModified());
			}
		}
	});
	return fList;
}

Leave a Reply

Your email address will not be published.