Monday, 25 April 2016

How to use FilenameFilter ?


Example
Implement FilenameFilter and override accept() which returns flag of filter condition.

// Implementing FilenameFilter
public class GenericExtFilter implements FilenameFilter {
  private String ext;
  public GenericExtFilter(String ext) {
    this.ext = ext;
  }
  public boolean accept(File dir, String name) {
    return (name.endsWith(ext));
  }
}

// Using filename filter subclass
GenericExtFilter filter = new GenericExtFilter(".txt");

private static final String FILE_DIR = "c:\\folder";
File dir = new File(FILE_DIR);
String[] list = dir.list(filter);

File file;
for (String file : list){
  String temp = new StringBuffer(FILE_DIR).append(File.separator)
                        .append(file).toString();
  System.out.println("File name : " + temp);

  file = new File(temp);
  // Use File object 'file'
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.