Menu
Topics Index
...
`

UsingFilenameFilter - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App