Apache Commons IO - PrefixFileFilter



PrefixFileFilter filters the files which are based on prefix.

Class Declaration

Following is the declaration for org.apache.commons.io.filefilter.PrefixFileFilter Class −

public class PrefixFileFilter
   extends AbstractFileFilter implements Serializable

Example of PrefixFileFilter Class

Here is the input file we need to parse −

Welcome to TutorialsPoint. Simply Easy Learning.

Let's print all files and directories in the current directory and then, filter a file with name starting with input.

IOTester.java

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.PrefixFileFilter;
public class IOTester {
   public static void main(String[] args) {
      try {
         usingPrefixFileFilter();
      } catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }
   public static void usingPrefixFileFilter() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
      System.out.println("\nFile starting with input\n");
      String[] filesNames = currentDirectory.list( new PrefixFileFilter("input") );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File with extenstion txt

input.txt
Advertisements