Get files with specific extension (.txt, .doc) in Java - list(FilenameFilter) and listFiles(FileFilter)

Java provides a handy way to select specific files from a given directory using Filters. Java has FilenameFilter interface with method accept(dirName, filename) which needs to be implemented by the instances of classes used to filter filenames.
For displaying all files/directories at given abstract path we use list() and listFiles(). Similarly we have
list(FilenameFilter filter) - Returns all files/directories name ,if it satisfies filter criteria
listFiles(FilenameFilter filter) - Returns all files/directories(File object),if it satisfies filter criteria.
Below sample program shows how to use FilenameFiler interface to display all files with extension .xml and .json files at given abstract path.
package com.devinline.javaio;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;

public class FilterInJavaIO {

 public static void main(String[] args) {
  File dirPath = new File("E:\\input");
  // Without Filter: Display all files/directories
  File[] fileListWithoutFilter = dirPath.listFiles();
  System.out.println("*******File/Directory names**********");
  for (File file : fileListWithoutFilter) {
   if (file.isDirectory())
    System.out.println("Dir name is " + file.getAbsolutePath());
   else
    System.out.println("File name is " + file.getAbsolutePath());
  }

  // With Filter: Display all files Name with .xml or .json extension
  String[] fileNamelistWithFilter = dirPath.list(new FilenameFilter() {
   @Override
   public boolean accept(File dir, String name) {
    if (name.endsWith(".json") || name.endsWith(".xml"))
     return true;
    else
     return false;
   }
  });
  System.out.println("\n*******Files name with "
    + "extension .xml or .json**********");
  for (String fileName : fileNamelistWithFilter) {
   System.out.println(fileName);
  }

  // With Filter: Display all files absolute path with .xml or .json extension
  File[] fileListWithFilter = dirPath.listFiles(new FileFilter() {
   @Override
   public boolean accept(File pathname) {
    if (pathname.getName().endsWith(".json")
      || pathname.getName().endsWith(".xml"))
     return true;
    else
     return false;
   }
  });
  System.out.println("\n*******Files absoulte path with "
    + "extension .xml or .json**********");
  for (File file : fileListWithFilter) {
   System.out.println(file.getAbsolutePath());
  }

 }
}
========Sample output======
*******File/Directory names**********
File name is E:\input\customerLog.json
Dir name is E:\input\doc
File name is E:\input\EmployeeDST.xml
Dir name is E:\input\extra
File name is E:\input\Install_doc.doc
File name is E:\input\install_doc.pdf
File name is E:\input\trailLog.json

*******File names with extension .xml or .json**********
customerLog.json
EmployeeDST.xml
trailLog.json

*******File's absolute path with extension .xml or .json**********
E:\input\customerLog.json
E:\input\EmployeeDST.xml
E:\input\trailLog.json
========================
In above example, first we displayed all files/directories at given abstract path("E:\\input").
For "Display all files Name with .xml or .json extension" an Instance of FilenameFilter interface passed to the list() methods anonymously and accept method is implemented with constraint if(Extension_of_file = .xml or .json) then return true. Method list() internally calls accept() method for each of the file present at that abstract location, If accept() returns true - file added to list fileNamelistWithFilter

Similarly, For "Display all files absolute path with .xml or .json extension", an instance of FileFilter passed to method listFiles() anonymously and if accept method returns ture then file is added to list fileListWithFilter.
 


1 Comments

Previous Post Next Post