Tutorialspoint examples

Learn java tutorial with examples for beginners online

How to filter the files by file extensions java


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

Example:

package com.tutorialspointexamples;
 
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.

Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status