June 24, 2022

Java Program to Get Files Having a Specific Extension

In this article we’ll see a Java program to get all the files having a specific extension from a directory.

FileNameFilter Interface in Java

In FilenameFilter interface there is method accept().

accept(File dir, String name)- Tests if a specified file should be included in a file list.

By implementing this method you can test each file in the passed directory. If file has a required extension then it is included otherwise discarded.

Another point is how to include the files with the given extension in a list, for that there is a File.list() method that takes instance of FilenameFilter.

String[] list(FilenameFilter filter)- Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

Java program to find files with specific extension

With this background information let’s write a Java program to get all the files in a given directory that have a ".txt" extension.

FileNameFilter is a functional interface that means it can also be implemented as a lambda expression. Following Java program implements FileNameFilter as a lambda expression.

public class FilteredFiles {
  public static void main(String[] args) {
    // Folder from which files are fetched
    File file = new File("F:\\knpcode");
    // Implemented as lambda. filter all the files
    // having .txt extension
    File[] fileList = file.listFiles((d,f)-> f.toLowerCase().endsWith(".txt"));
    // Listing all the included files
    for(File f : fileList) {
      System.out.println(f.getAbsolutePath());
    }
  }
}
Same thing can be done by implementing FileNameFilter as an anonymous class.
public class FilteredFiles {
  public static void main(String[] args) {
    // Folder from which files are fetched
    File file = new File("F:\\knpcode");
    // Implemented as lambda. filter all the files
    // having .txt extension
    File[] fileList = file.listFiles(new FilenameFilter() {			
      @Override
      public boolean accept(File dir, String name) {
        if(name.toLowerCase().endsWith(".txt"))
          return true;
        else 
          return false;
      }
    });
							
    // Listing all the included files
    for(File f : fileList) {
      System.out.println(f.getAbsolutePath());
    }
  }
}

That's all for the topic Java Program to Get Files Having a Specific Extension. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment