In this section we will be showing source code on how to list files in ascending or descending order by filename. We will be using extensively the Collections class sort method. Calling the Collections.sort with only with one argument which is list, the list is sorted by default in ascending order. However if a comparator is placed as the second argument of the sort method, it will take into precedence that sorting method is relying on the logic of the comparator. Since we are only interested in getting the list sorted into ascending or descending order we will not be showing on how to use a custom comparator. Instead we will only be using the reverseOrder order method of the Collections class. This method returns a comparator which sorted the input list into descending order.
One notable method use on this source code is the usage of Arrays.asList method which convert array into list. We used this since we are taking into account the usage of Collections.sort method which takes List as an input parameter.
Java : Source code to sort filenames into descending or descending
package com.javatutorialhq.tutorial; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; public class SortFileName { /** * This sample code shows * how to sort filenames in ascending or descending order * Property of javatutorialhq.com * All Rights Reserved * Version 1.0 * 06/21/2012 */ public static void main(String[] args) { File fileDir = new File("C:\\temp"); if(fileDir.isDirectory()){ List listFile = Arrays.asList(fileDir.list()); System.out.println("Listing files unsorted"); for(String s:listFile){ System.out.println(s); } Collections.sort(listFile); System.out.println("---------------------------------------"); System.out.println("Sorting by filename in ascending order"); for(String s:listFile){ System.out.println(s); } System.out.println("---------------------------------------"); System.out.println("Sorting by filename in descending order"); Collections.sort(listFile,Collections.reverseOrder()); for(String s:listFile){ System.out.println(s); } } else{ System.out.println(fileDir.getAbsolutePath() + " is not a directory"); } } }
Sample output
Listing files unsorted aspnet_client files ftp_transfer New Briefcase sourcefolder target targetfolder test.log testFolder --------------------------------------- Sorting by filename in ascending order New Briefcase aspnet_client files ftp_transfer sourcefolder target targetfolder test.log testFolder --------------------------------------- Sorting by filename in descending order testFolder test.log targetfolder target sourcefolder ftp_transfer files aspnet_client New Briefcase[/fusion_builder_column][/fusion_builder_row][/fusion_builder_container]