Filters file-names for a name.

Class Declaration

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

  1. public class NameFileFilter
  2. extends AbstractFileFilter implements Serializable

Example of NameFileFilter 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 whose name is Input.txt.

IOTester.java

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

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 name input.txt
  11.  
  12. input.txt