Filters files based on prefix.

Class Declaration

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

  1. public class PrefixFileFilter
  2. extends AbstractFileFilter implements Serializable

Example of PrefixFileFilter Class

Here is the input file we need to parse −

  1. 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

  1. import java.io.File;
  2. import java.io.IOException;
  3.  
  4. import org.apache.commons.io.filefilter.PrefixFileFilter;
  5.  
  6. public class IOTester {
  7. public static void main(String[] args) {
  8. try {
  9. usingPrefixFileFilter();
  10. } catch(IOException e) {
  11. System.out.println(e.getMessage());
  12. }
  13. }
  14.  
  15. public static void usingPrefixFileFilter() throws IOException {
  16. //get the current directory
  17. File currentDirectory = new File(".");
  18.  
  19. //get names of all files and directory in current directory
  20. String[] files = currentDirectory.list();
  21. System.out.println("All files and Folders.n");
  22. for( int i = 0; i < files.length; i++ ) {
  23. System.out.println(files[i]);
  24. }
  25.  
  26. System.out.println("nFile starting with inputn");
  27. String[] filesNames = currentDirectory.list( new PrefixFileFilter("input") );
  28. for( int i = 0; i < filesNames.length; i++ ) {
  29. System.out.println(filesNames[i]);
  30. }
  31. }
  32. }

Output

It will print the following result.

  1. All files and Folders.
  2.  
  3. .classpath
  4. .project
  5. .settings
  6. bin
  7. input.txt
  8. src
  9.  
  10. File with extenstion txt
  11.  
  12. input.txt