Friday, July 19, 2013

FilenameFilter

FilenameFilter is an interface used to filter filenames. FilenameFilter has a special method called accept that returns a boolean value (true or false). The accept(File dir, String name) method allows you to filter filenames. For example, you may want to show only Java files (*.java) in a directory. To accomplish this task, in the accept method you need to test whether the name argument ends with .java. To use the FilenameFilter interface, You will need a class that implements it. Then create an instance of the class and supply this object to the list method of the File instance.

Example: show only java files from d:/myprogram directory

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

public class FilesList{

public static void main(String[] args){

showFileNames("d:/myprogram","java");

}

public static void showFileNames(String src, String ext){

File f=new File(src); //create file object to connect to the source directory
if(!f.exists()){
System.out.println("Source directory does not exist.");
System.exit(-1);
}

String[] filenames;
if(!ext.equals("")){
filenames=f.list(new ExtFilter(ext)); //list files by extension
for(String name:filenames){
System.out.println(name);
}
}


}



}

class ExtFilter implements FilenameFilter{
String ext="";
public ExtFilter(String ext){
this.ext="."+ext;
}
public boolean accept(File f, String name){
if(name.endsWith(ext)) return true;
else return false;

}
}

2 comments:

  1. I create a simple application that allows the user to select a file from the JFileChooser dialog. I want the dialog show on the image files such as jpg, bmp, gif, png, tiff. Is it possible in Java to filter the files in the JFileChooser dialog?

    ReplyDelete
    Replies
    1. Yes. It is possible in Java to filter file names in JFileChooser component by using the FileNameExtensionFilter class. Try the following code below.
      JFileChooser chooser = new JFileChooser();
      FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif","png","bmp");
      chooser.setFileFilter(filter);

      Delete