Compare the names of two files. NameFileComparator can be used to sort lists or arrays of files using their name either in a case-sensitive, case-insensitive or system dependent case sensitive way.

Class Declaration

Following is the declaration for org.apache.commons.io.comparator.NameFileComparator Class −

  1. public class NameFileComparator
  2. extends Object implements Serializable

Example of NameFileComparator 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.IOCase;
  6. import org.apache.commons.io.comparator.NameFileComparator;
  7. import org.apache.commons.io.filefilter.FileFileFilter;
  8.  
  9. public class IOTester {
  10. public static void main(String[] args) {
  11. try {
  12. usingNameFileComparator();
  13. } catch(IOException e) {
  14. System.out.println(e.getMessage());
  15. }
  16. }
  17.  
  18. public static void usingNameFileComparator() throws IOException {
  19. //get the current directory
  20. File currentDirectory = new File(".");
  21.  
  22. NameFileComparator comparator = new NameFileComparator(IOCase.INSENSITIVE);
  23.  
  24. File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
  25.  
  26. System.out.println("Sorted By Name: ");
  27. for(File file:sortedFiles) {
  28. System.out.println(file.getName());
  29. }
  30. }
  31. }

Output

It will print the following result.

  1. Sorted By Name:
  2. .classpath
  3. .project
  4. input.txt