Menu
Topics Index
...
`


Input/Output: Exploring java.io > File >
Siva Nookala - 06 Apr 2016
FilenameFilter filters the files that match a certain filename pattern, or filter.

String[] list(FilenameFilter FFObj)
In the above form FFObj is an object of a class that implements the FilenameFilter interface. FilenameFilter defines only a single method, accept(), which is called once for each file in a list. Its general form is given below:
boolean acceptFile(File directory, String filename)
The accept() method return true for files in the directory specifed by directory that match the filename argument and return false for those files that should be excluded.
UsingFilenameFilter
import java.io.*;

class OnlyExt implements FilenameFilter
{
    String ext;
    
        public OnlyExt(String ext)
        {
            this.ext = "." + ext;
        }
    
        public boolean accept(File dir, String name)
        {
            return name.endsWith(ext);
        }
}

public class UsingFileNameFilterDemo
{
    public static void main(String[] args)
    {
        String dirname = "C://Myfolder"; // LINE A
        File f1 = new File(dirname); // LINE B
        String[] allFiles = f1.list(); // LINE C

        System.out.println("Printing all files in the directory.");
        for(int i = 0; i < allFiles.length; i++)
        {
            System.out.println(allFiles[i]);
        }
        System.out.println("-----------------------");

        FilenameFilter only = new OnlyExt("html"); // LINE D
        System.out.println("Printing files after filtering.");
        String s[] = f1.list(only); // LINE E
        for(int i = 0; i < s.length; i++)
        {
            System.out.println(s[i]);
        }

    }

}
OUTPUT

Printing all files in the directory.
HomePage.html
Introduction.txt
Login.html
Logout.html
Maintainance.txt
UserDetails.xls
-----------------------
Printing files after filtering.
HomePage.html
Login.html
Logout.html

DESCRIPTION

In the above program OnlyExt class implements FilenameFilter interface and implements the method accept.
At LINE A we created the path for directory.
At LINE B we created the File object.
At LINE C we converting the files in the directory to list.
At LINE D we created OnlyExt object and passed the String html. So that only .html files are retrieved from file directory.
At LINE E we are invoking the list(FilenameFilter filter) method on File f1.

THINGS TO TRY
  • Try to filter the files in your local directory.
In the above program OnlyExtis the class which implements FilenameFilter interface and implements accept method.
Note : The output is based on the files in your directory and will not same for all machines.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.