FilenameFilter的使用

声明:本文从《Java编程思想》第四版18章 整理

假设我们想查看一个目录列表,可以使用两种方法来使用File对象。如果我们调用不带参数的list()方法,便可以获得此File对象包含的全部列表。然而,如果我们想获得一个受限的列表,例如,想得到所有扩展名为.java的文件,那么我们就要用到“目录过滤器”。

首先看我的D盘目录:

1. 使用不带参数的list()方法获得所有的File对象

package com.io;

import java.io.File;

/**
 * @Author: LiuZG
 * @Date: 2019/1/2812:35
 * @Description:
 */
public class DirListWithoutArgs {
    public static void main(String[] args){
        File path = new File("D:\\");
        // list all File object
        String[] list = path.list();
        //print
        for (String file : list){
            System.out.println(file);
        }
    }
}

程序输出:略。

如果想列出D盘根目录下所有以“.java”为结尾的文件该怎么办呢?这是我们就需要用到FilenameFilter这个接口,具体例子如下:

package com.io;

import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;

/**
 * @Author: LiuZG
 * @Date: 2019/1/289:05
 * @Description: 列出D盘根目录下所有以.java为结尾的文件名
 */
public class DirList {
    public static void main(String[] args){
        File path = new File("D:\\");
        //以.java为结尾的文件
        String[] list = path.list(new DirFilter(".*\\.java"));
        for (String name : list){
            System.out.println(name);
        }
    }
}

class DirFilter implements FilenameFilter{
    private Pattern pattern;
    public DirFilter(String regex){
        pattern = Pattern.compile(regex);
    }
    public boolean accept(File dir,String name){
        return pattern.matcher(name).matches();
    }
}

程序输出如下:

以上为FilenameFilter的基本用法。

有兴趣的朋友可以查看FilenameFilter这个接口的源代码:

/*
 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.io;

/**
 * Instances of classes that implement this interface are used to
 * filter filenames. These instances are used to filter directory
 * listings in the <code>list</code> method of class
 * <code>File</code>, and by the Abstract Window Toolkit's file
 * dialog component.
 *
 * @author  Arthur van Hoff
 * @author  Jonathan Payne
 * @see     java.awt.FileDialog#setFilenameFilter(java.io.FilenameFilter)
 * @see     java.io.File
 * @see     java.io.File#list(java.io.FilenameFilter)
 * @since   JDK1.0
 */
@FunctionalInterface
public interface FilenameFilter {
    /**
     * Tests if a specified file should be included in a file list.
     *
     * @param   dir    the directory in which the file was found.
     * @param   name   the name of the file.
     * @return  <code>true</code> if and only if the name should be
     * included in the file list; <code>false</code> otherwise.
     */
    boolean accept(File dir, String name);
}

 该接口只需要实现一个accept方法。DirFilter这个类存在的唯一原因就是accept()方法。创建这个类的目的在于把accept()方法提供给list()用,使list()可以回调accept(),进而决定哪些文件包含在列表中。

 

posted on 2019-01-28 12:52  tinylight1991  阅读(278)  评论(0)    收藏  举报

导航