Compare the sizes of two files/directory. SizeFileComparator can be used to sort lists or arrays of files using their size or directories based on their no. of children.

Class Declaration

Following is the declaration for org.apache.commons.io.comparator.SizeFileComparator Class -

  1. public class SizeFileComparator
  2. extends Object implements Serializable

Example of SizeFileComparator Class

Here is the input file we need to parse −

  1. Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

  1. import java.io.File;
  2. import java.io.FileFilter;
  3. import java.io.IOException;
  4.  
  5. import org.apache.commons.io.comparator.SizeFileComparator;
  6. import org.apache.commons.io.filefilter.FileFileFilter;
  7.  
  8. public class IOTester {
  9. public static void main(String[] args) {
  10. try {
  11. usingSizeFileComparator();
  12. } catch(IOException e) {
  13. System.out.println(e.getMessage());
  14. }
  15. }
  16.  
  17. public static void usingSizeFileComparator() throws IOException {
  18. //get the current directory
  19. File currentDirectory = new File(".");
  20.  
  21. SizeFileComparator comparator = new SizeFileComparator();
  22.  
  23. File[] sortedFiles =
  24. comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
  25.  
  26. System.out.println("Sorted By Size: ");
  27. for(File file:sortedFiles) {
  28. System.out.println(file.getName() + ", size(kb) :" + file.length());
  29. }
  30. }
  31. }

Output

It will print the following result.

  1. Sorted By Size:
  2. input.txt, size:124
  3. .project, size:382
  4. .classpath, size:441