Java FilenameFilter interface

Introduction

You can limit the number of files returned by the list() method, use a file filter.


// Directory of .HTML files. 
import java.io.File;
import java.io.FilenameFilter;

class OnlyExt implements FilenameFilter {
  String ext;//w w w .j a va  2s.  c  om

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

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

public class Main {
  public static void main(String args[]) {
    String dirname = "c:/";
    File f1 = new File(dirname);
    FilenameFilter only = new OnlyExt("html");
    String s[] = f1.list(only);
    for (int i = 0; i < s.length; i++) {
      System.out.println(s[i]);
    }
  }
}



PreviousNext

Related