Commons Io 简明教程

Apache Commons IO - SizeFileComparator

SizeFileComparator 比较两个文件/目录的大小。可以根据其大小对文件列表或数组进行排序,也可以根据其子项数对目录进行排序。

Class Declaration

以下是声明:

org.apache.commons.io.comparator.SizeFileComparator 类 −

public class SizeFileComparator
   extends Object implements Serializable

Example of SizeFileComparator Class

以下是我们需要解析的输入文件 -

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

它将打印以下结果。

Sorted By Size:
input.txt, size:124
.project, size:382
.classpath, size:441