Wednesday 11 March 2020

Sort files by their name

Using a custom comparator, we can sort the files by their name.

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

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

public class FileNameComparator implements Comparator<File> {

 @Override
 public int compare(File file1, File file2) {
  return file1.getName().compareTo(file2.getName());
 }

}

App.java

package com.sample.app;

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

import com.sample.app.comparator.FileNameComparator;

public class App {

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

   System.out.println(file.getName());
  }
 }

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

  File[] files = directory.listFiles();

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

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

  File[] files1 = sortByName(directoryPath);

  printFiles(files1);
 }

}


You may like

No comments:

Post a Comment