Topics Index

ListFiles Alternattive - Java Example Program

ListFiles Alternattive
class FileFiltering
    public static void main(String arg[])
        File f = new File("C:\\"); // LINE A
        FilenameFilter fnf = new Extension(".mp4");
        File[] farray = f.listFiles(fnf); // LINE B
        for(int i =0; i < farray.length; i++)
            System.out.println(farray[i]);  // LINE C
        FileFilter ff = new CheckFilter();
        File ffarray[] = f.listFiles(ff); // LINE D
        for(int i =0; i < ffarray.length; i++)

class Extension implements FilenameFilter
    String name;
    public Extension(String name)
    { = name;
    public boolean accept(File dir, String name)
        return name.endsWith(;
class CheckFilter implements FileFilter
    public boolean accept(File pathname)
        return pathname.toString().endsWith("jpg");

C:\Java Beginner Tutorial 4.mp4
C:\Java Programming Tutorial 3.mp4
C:\Java Tutorial for beginners 2.mp4
C:\Java Tutorial for Beginners.mp4


In the above program we have two classes apart from main class. Extension implements FilenameFilter and implements accept method which filters files that end with the extension .mp4 and CheckFilter implements FileFilter and implements accept method which filters files that end with the extension .jpg
At LINE A we created a File Object and set the path to drive C:
At LINE B we are invoking the listFiles(FilenameFilter ffobj) method
At LINE C we are printing the File objects obtained from listFiles method.
At LINE D we are invoking listFiles(FileFilter fobj) method.

  • Obtain all text files from C: with listFiles(FilenameFilter ffobj)
  • Obtain all the directories in drive C: with listFiles(FileFilter fobj)

© meritcampus 2019

All Rights Reserved.

Open In App