Search the Site

Sponsors

bottom corner

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

This is a sample Java method that can be used to sort an array of Java's File objects by the last modified date, either in ascending or descending order.

This page is filed under keyword(s): 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;
}

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): java.
Author: C. Peter Chen
Last updated: 27 May 2008

bottom corner