例子
以下示例显示java.io.File.list(FilenameFilter filter)方法的用法。
package com.jc2182;
import java.io.File;
import java.io.FilenameFilter;
public class FileDemo implements FilenameFilter {
String str;
// constructor takes string argument
public FileDemo(String ext) {
str = "."+ext;
}
// main method
public static void main(String[] args) {
String[] paths;
try {
// create new file
f = new File("c:/test");
// create new filter
FilenameFilter filter = new FileDemo("txt");
// array of files and directory
paths = f.list(filter);
// for each name in the path array
for(String path:paths) {
// prints filename and directory name
System.out.println(path);
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
@Override
public boolean accept(File dir, String name) {
return name.endsWith(str);
}
}
让我们编译并运行以上程序,这将产生以下结果-