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.

/****************************************************************************************
 * Created on 08-2011 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

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

/**
 * Created by http://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());
        }
    }

}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.