Tuesday, April 19, 2011

A Java FileFilter example

The Filter File Java example code provides the following functionalities:
  • Filtering the files depending on the file extension provided by the user
  • User provides the file extension and then program lists all the matching files found
We can write our own file filter which implements FilenameFilter, so it has to implement accept method.

Example

class MyFilter implements FilenameFilter{

  String ext;

 
 public MyFilter(String ext){
  
    this.ext="." + ext;
  }
  

  public boolean accept(File dir,String name){
  
    return name.endsWith(ext);
  }
}


So constructor takes argument as extenstion, which it has to filter.

Using our filter:

public class MyFilterUser{
 
 public static void main(String args[]) throws IOException{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Please enter the directory name : ");

    String dir = in.readLine();

    System.out.println("Please enter file type : ");

      String extn = in.readLine();
   
     File f = new File(dir);

    FilenameFilter ff = new MyFilter(extn);
    
    String s[] = f.list(ff);


    for (int i = 0; i < s.length; i++){
  
      System.out.println(s[i]);

    }
  
  }

}

No comments:

Post a Comment

Chitika