How can I sort a directory list by name, size and last modification?

advertisements

I'm just trying to figure out how I can sort a directory listing according to it's name, time last modified and size. I know you can access the file's name, size, last modified with the File methods but I'm not sure how to go about sorting it. If someone can point me in the right direction it would great.

public void printDirectoryContents(String path, PrintWriter writer)
{
    File[] list = root.listFiles();
    Arrays.sort(list);

    for ( File f : list )
    {
        String name = f.getName();
        long lastmod = f.lastModified();
        SimpleDateFormat simple = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
        String formatted = simple.format(new Date(lastmod));
        long length = f.length();

    }
}


You should implement a Comparator to sort the files based on the attributes you mentioned, and pass this as an argument to the Arrays.sort method.

    Arrays.sort(list, new Comparator<File>()
    {
        public int compare(File file1, File file2)
        {
            int result = ...
            .... comparison logic
            return result;
        }
    });