java中的FileFilter接口如何使用

来源:互联网 发布:unity3d 游戏手柄 编辑:程序博客网 时间:2024/06/08 05:47
public File[] listFiles(FileFilter filter)
返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录。除了返回数组中的路径名必须满足过滤器外,此方法的行为与 listFiles() 方法相同。如果给定filternull,则接受所有路径名。否则,当且仅当在路径名上调用过滤器的 FileFilter.accept(java.io.File) 方法返回true 时,该路径名才满足过滤器。

下面是一个简单的例子

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package contcurrentandalgorithm;

import java.io.File;
import java.io.FileFilter;

/**
 *
 * @author Administrator
 * zyyjiao@mail.ustc.edu.cn
 */
public class FileFilterTest implements FileFilter {

    String content = "";

    public FileFilterTest(String condition) {
        this.content = condition;
    }

    @Override
    public boolean accept(File pathname) {
        // TODO Auto-generated method stub 
        String filename = pathname.getName();
        if (filename.lastIndexOf(content) != -1) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub 
        File root = new File("D://zyyjiao");
        if (!root.exists()) {
            root.mkdir();
        }
        File[] files;
        files = root.listFiles(new FileFilterTest(".txt"));
        if (files.length != 0) {
            for (int i = 0; i < files.length; i++) {
                System.out.println(files[i].getAbsolutePath());
            }
        }
    }
}