Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

True enough. Why do I have to write this:

  SingleFilenameFilter myFilenameFilter = new SingleFilenameFilter()
  List myList = new File("/tmp").listFiles(myFilenameFilter)
Why should I have to create a class that implements FilenameFilter, just to filter on some file names? Especially in a one-off instance, why should I have to create a class that I will only ever use once?

Why isn't there a default implementation? Something like:

  public class RegexFilenameFilter implements FilenameFilter {
    private String regex;
    public RegexFilenameFilter(String re) {
      this.regex = re;
    }
    public accept(File dir, String name) {
     // matching here
    }
  }
Then I could just write:

  List relevantFiles = new File("/tmp").listFiles(new RegexFilenameFilter("^tmp\\.[a-z0-9]+$"))
Why should I have to create this class for every project (or create my own little 'utils' library)? It's easily one of the simplest usages of a FilenameFilter.


anonymous inner classes are your friend (poor mans closure):

  File[] textFiles = directory.listFiles(new FileFilter() {
    public boolean accept(File file) {
      return file.isFile() && file.canRead() && file.getName().endsWith(".txt");
    }
  });


File enumeration has sucked for a long time in Java. java.nio.file should hopefully fix this in 1.7, but I haven't had a chance to play with it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: