How to filter specific type of Files using FileFilter class in java?

Below java code show how to filter specific type of files using FileFilter class –

To implement the FileFilter interface we need to create an accept() method which takes a object as parameter. In the method we check wheter the name ends with “.txt” and if so we return true, else false.

When we have created the FileFilter we can pass it to the listFiles method of the class which will use it to return an array of all files that the filter returned true for in its accept method.

[java toolbar=”true”]
* Created on 08-2011 Copyright(c) All Rights Reserved.
package com.kodehelp.javaio;


* Created by
* Date: 8/30/11
public class FileFilterExample {

//create a FileFilter and override its accept-method
static FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
//if the file extension is .txt return true, else false
if (file.getName().endsWith(".txt")) {
return true;
return false;

public static void main(String args[]){
File file = new File("/tmp");
System.out.println("No Directory Specified");
File[] files = file.listFiles(fileFilter);

for (File f : files) {