How to filter the files by file extensions java

We need to implement FilenameFilter class and override accept() method.

Example:

package com.w3spoint;
 
import java.io.File;
import java.io.FilenameFilter;
 
public class FilesFilter {
  public static void main(String args[]){
	 File file = new File("D:/Test files/");
	 String[] files = file.list(new FilenameFilter() {
 
         @Override
         public boolean accept(File dir, String name) {
             if(name.toLowerCase().endsWith(".txt")){
                 return true;
             } else {
                 return false;
             }
         }
     });
     for(String f:files){
         System.out.println(f);
     }
  }
}

Output:

newTest.txt

Download this example.

Content Protection by DMCA.com
Please Share