Wednesday 11 March 2020

Sort files by their size

Approach 1: Using a comparator
public class FileSizeComparator implements Comparator<File> {

 @Override
 public int compare(File file1, File file2) {
  long file1Length = file1.length();
  long file2Length = file2.length();

  if (file1Length > file2Length)
   return 1;
  else if (file1Length < file2Length)
   return -1;
  return 0;
 }

}

public static File[] sortByLengthApproach1(String directoryPath) {
 File directory = new File(directoryPath);

 File[] files = directory.listFiles();

 Arrays.sort(files, new FileSizeComparator());
 return files;
}


Approach 2: Using Comparator.comparingLong
public static File[] sortByLengthApproach2(String directoryPath) {
 File directory = new File(directoryPath);

 File[] files = directory.listFiles();
 Arrays.sort(files, Comparator.comparingLong(File::length));
 return files;
}

Find the below working application.

FileSizeComparator.java
package com.sample.app.comparator;

import java.io.File;
import java.util.Comparator;

public class FileSizeComparator implements Comparator<File> {

 @Override
 public int compare(File file1, File file2) {
  long file1Length = file1.length();
  long file2Length = file2.length();

  if (file1Length > file2Length)
   return 1;
  else if (file1Length < file2Length)
   return -1;
  return 0;
 }

}

App.java

package com.sample.app;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;

import com.sample.app.comparator.FileSizeComparator;

public class App {

 private static void printFiles(File[] files) {
  for (File file : files) {

   System.out.println(file.length() + "\t" + file.getName());
  }
  System.out.println("\n************************\n");
 }

 public static File[] sortByLengthApproach1(String directoryPath) {
  File directory = new File(directoryPath);

  File[] files = directory.listFiles();

  Arrays.sort(files, new FileSizeComparator());
  return files;
 }
 
 public static File[] sortByLengthApproach2(String directoryPath) {
  File directory = new File(directoryPath);

  File[] files = directory.listFiles();
  Arrays.sort(files, Comparator.comparingLong(File::length));
  return files;
 }

 public static void main(String[] args) {
  String directoryPath = "/Users/krishna/Documents/TechnicalDocuments";

  File[] files1 = sortByLengthApproach1(directoryPath);
  File[] files2 = sortByLengthApproach2(directoryPath);

  printFiles(files1);
  printFiles(files2);
 }

}


You may like

No comments:

Post a Comment