Real'sHowTo AddThis Feed Button
Custom Search

Get the content of a directory with a FilterTag(s): IO


First you create a class that implements java.io.FilenameFilter and then code the accept() method. You call File.list() with the filter as a parameter. The returned array of strings has all the names that passed through the accept()filter.
import java.io.File;
import java.io.FilenameFilter;

public class Filter implements FilenameFilter {
  protected String pattern;
  public Filter (String str) {
    pattern = str;
  }

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

  public static void main (String args[]) {
    if (args.length != 1) {
       System.err.println
          ("usage: java Filter <pattern list>  ex. java Filter java");
       return;
    }

    Filter nf = new Filter (args[0]);
    // current directory
    File dir = new File (".");
    String[] strs = dir.list(nf);
    for (int i = 0; i < strs.length; i++) {
      System.out.println (strs[i]);
    }
  }
}
Here a version to support multiple filters.
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeSet;

/**
* <CODE>
* GenericFileFilter xml = new GenericFileFilter ("xml");
* // GenericFileFilter xmlandpdf = new GenericFileFilter (new String [] { "xml", "pdf" });
* File dir = new File (".");
* String[] strs = dir.list(xml);
* for (int i = 0; i < strs.length; i++) {
* // strs[i]
* }
* </CODE>
*/

public class GenericFileFilter implements FilenameFilter {
private TreeSet<String> exts = new TreeSet<String>() ;

public GenericFileFilter(String ext) {
  exts.add("." + ext.toLowerCase().trim());
}


public GenericFileFilter(String[] extensions) {
  Iterator<String> extList = Arrays.asList(extensions).iterator();
  while (extList.hasNext()) {
    exts.add("." + extList.next().toLowerCase().trim());
  }
  exts.remove("");
}

public boolean accept(File dir, String name) {
  final Iterator<String> extList = exts.iterator();
  while (extList.hasNext()) {
    if (name.toLowerCase().endsWith(extList.next())) {
      return true;
    }
  }
  return false;
}
}
If multiple extensions are to be checked then a regular expression can be used.
import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.*;

public class Filter implements FilenameFilter {

  public boolean accept (File dir, String name) {
    return Pattern.matches(".*\\.(jpg|jpeg|gif|png|bmp)", name);
    //  if only one extension to check :  "\\.jpg"
  }

  public static void main (String args[]) {
    if (args.length < 1) {
       System.err.println
          ("usage: java Filter <directory>  ex. java Filter c:\\temp");
       return;
    }
    Filter nf = new Filter();
    // current directory
    File dir = new File (args[0]);
    String[] strs = dir.list(nf);
    for (int i = 0; i < strs.length; i++) {
      System.out.println (strs[i]);
    }
  }
}

If your need is simple then you don't need a complete class to implement a FilenameFilter. You can declare an anonymous class with this simple onle-liner.

import java.io.File;
import java.io.FilenameFilter;
...
files = dir.listFiles(new FilenameFilter() {
           public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".txt");
                }
           }
        );

To retrieve only directories, a simple filter can be made.
import java.io.File;
import java.io.FileFilter;

public class Test {
  public static void main(String[] args) throws Exception {

    File [] foldersToBeChecked =
      new File("J:\\").listFiles
      (new  FileFilter() {
        public boolean accept(File pathname) {
          return (pathname.isDirectory());
        }
      }
      );
    for(File f : foldersToBeChecked) {
      System.out.println(f);
    }
  }
}

blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]