get file list from a folder filtered by extensions java

The listFiles() method is used to get file list from a folder.

Example:

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

Output:

file1.docx
file2.docx

Download this example.

Content Protection by DMCA.com
Please Share