String name = file.getName( ); // find the last int idx = name.lastIndexOf("."); if(index == -1) { return false; } else if(index == name.length( ) -1) { return false; } else { return this.extension.equals(name.substring(index+1)); } } } 以下的例子中用到了上述的ExtensionFileFilter 代碼: ... String dir = "..."; // directory of your choice File file = new File(dir); File[] files = file.listFiles(new ExtensionFileFilter("cfg"));
// files variable is now c:*.cfg if 'dir' is c: // that is, all the files in the specified directory ending in *.cfg ... FileFilter 其實是從 javax.swing.filechooser.FileFilter派生出來的,javax.swing.filechooser.FileFilter 是使用JFileChoosers的抽象類。