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 java.io.File 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 java.io.File 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) https://kodehelp.com All Rights Reserved.
****************************************************************************************/
package com.kodehelp.javaio;

import java.io.File;
import java.io.FileFilter;

/**
* Created by https://kodehelp.com
* 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");
if(!file.isDirectory()){
System.out.println("No Directory Specified");
return;
}
File[] files = file.listFiles(fileFilter);

for (File f : files) {
System.out.println(f.getName());
}
}

}
[/java]