This question already has an answer here:
The directory has n number of files.I am creating class, it will sort files by size from directory using java arraylist.
I can read the file name and size. but how to sort the files by size?
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class SortingFiles
{
public static void main(String[] args)
{
File dir=null;
File[] paths;
final ArrayList<String> al= new ArrayList<String>();
try{
// create new file object
dir = new File("D:\\New folder\\New");
// array of files and directory
paths = dir.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for(File file:paths)
{
// prints filename and directory name
System.out.println(file.getName()+" - " +file.length() );
al.add(file.getName());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
i have tried to sort the file by size
for(int i=1; i<al.size(); i++)
{
System.out.println("\n Aftr : " +al.get(i) );
}
But it is not working.. Any one can help me..I am trying without "import org.apache.commons.io.FileUtils;". So what to do ?
Use a (
name
,size
) object inal
then sort with a customComparator
(or make this custom objectComparable
) usingCollections.sort
. Something like:then:
Not tested, not even compiled (typed here)
You have to create a String long hashmap then put key as filename, and length and value, then sort the hashmap by value using natural order.
I have completed. Thanks for your help.