Menu
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
        }
        System.out.println("------------------------");
        
        FileFilter ff = new CheckFilter();
        File ffarray[] = f.listFiles(ff); // LINE D
        
        for(int i =0; i < ffarray.length; i++)
        {
            System.out.println(ffarray[i]);
        }    
    }
}

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

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
------------------------
C:\20140626_123436.jpg
C:\20140626_123455.jpg
C:\20140626_123511.jpg
C:\20140626_123525.jpg

DESCRIPTION

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.

THINGS TO TRY
  • 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