Contact at mumbai.academics@gmail.com or 8097636691
Responsive Ads Here

Saturday, 30 June 2018

Apache Commons IO - SizeFileComparator

Apache Commons IO - SizeFileComparator



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 -
public class SizeFileComparator
   extends Object implements Serializable

Example of SizeFileComparator Class

Here is the input file we need to parse −
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import org.apache.commons.io.comparator.SizeFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try {
         usingSizeFileComparator();
      } catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }

   public static void usingSizeFileComparator() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");

      SizeFileComparator comparator = new SizeFileComparator();

      File[] sortedFiles = 
         comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));

      System.out.println("Sorted By Size: ");
      for(File file:sortedFiles) {      
         System.out.println(file.getName() + ", size(kb) :" + file.length());
      }
   }
}

Output

It will print the following result.
Sorted By Size: 
input.txt, size:124
.project, size:382
.classpath, size:441

No comments:

Post a Comment