How to get list of files using FileFilter class in java?

Below java code shows how to get list of files using FileFilter class.

FileFilter is an abstract class used by JFileChooser for filtering the set of files shown to the user. A FileFilter can be set on a JFileChooser to keep unwanted files from appearing in the directory listing.

 

/****************************************************************************************
 * 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());
        }
    }

}

Reference: Java Docs

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.