How to use FilenameFilter by an example code


By running the following code, only the .log file will be listed by implementing FilenameFilter.

The vital method for this code is public boolean accept used to Filter all files inside a directory.


import java.io.File;
import java.io.FilenameFilter;

public class FileNameFilterExample{

/**
 * @param FilenameFilter example
 */
 public static void main(String[] args) {

 File c = new File ("C:\\");
 FileNameFilterExample mainClass = new FileNameFilterExample();
 FileNameFilterExample.FileNameFiltering filter = mainClass.new FileNameFiltering();

 String [] fileNames = c.list(filter);
 for(String fileName : fileNames) {
 System.out.println(fileName);
 }

 }

public class FileNameFiltering implements FilenameFilter {

@Override
 public boolean accept(File dir, String name) {
 // listing only .log files
 return name.endsWith(".log");
 }

 }

}

Sample output of the code;

a – Copy (2).log
a – Copy (3).log
a – Copy (4).log
a – Copy (5).log
a – Copy.log
a.log

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s