您的位置 首页 java

夯实基础:图解 Java IO之FilenameFilter源码

从上一篇 图解 java io : 一、 File 源码 并没有把所有File的东西讲完。这次讲讲Filename filter ,关于过滤器文件《Think In Java》中写道:

更具体地说,这是一个策略模式的例子,因为list()实现了基本功能,而按着形式提供了这个策略,完善list()提供服务所需的算法。

java.io.FilenameFilter是文件名过滤器接口,即过滤出符合规则的文件名组。

一、FilenameFilter源码

从IO的UML可以看出, FilenameFilter接口独立 ,而且 没有 它的 实现类 。下面就看看它的源码:

public interface FilenameFilter {
 /**
 * 测试指定文件是否应该包含在某一文件列表中。
 *
 * @param 被找到的文件所在的目录。
 * @param 文件的名称
 */ boolean  accept (File dir, String name);
}
 

从JDK1.0就存在了,功能也很简单:就是为了 过滤文件名 。只要在accept()方法中传入相应的目录和文件名即可。

深度分析:接口要有真正的实现才能算行为模式中真正实现。 所以这里使用的是 策略模式 ,涉及到三个角色:

环境(Context)角色

抽象 策略(Strategy)角色

具体策略(Context Strategy)角色

结构图如下:

其中, FilenameFiler Interface 就是这里的 抽象策略角色 。其实也可以用 抽象类 实现。

但是,装饰器模式也有缺点:在编写程序的时候,它提供了相当多的灵活性( 容易混合和匹配属性 ),同时也增加了代码的 复杂性

二、使用方法

如图 FilenameFiler使用如图所示。上代码吧:(small 广告是要的,代码都在 开源项目 java-core-learning。 地址

package org.javacore.io;
import java.io.File;
import java.io.FilenameFilter;
/*
 * Copyright [2015] [Jeff Lee]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * 
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *//**
 * @author Jeff Lee
 * @since 2015-7-20 13:31:41
 * 类名过滤器的使用
 */public class FilenameFilterT {
public static void main(String[] args) {
// IO包路径
String dir = "src" + File.separator +
"org" + File.separator +
"javacore" + File.separator +
"io";
File file = new File(dir);
// 创建过滤器文件
MyFilter filter = new MyFilter("y.java");
// 过滤
String files[] = file.list(filter);

// 打印
for (String name : files) {
System.err.println(name);
}
}

/**
 *内部类实现过滤器文件接口
 */static class MyFilter implements FilenameFilter {

private String type;

public MyFilter (String type) {
this.type = type;
}
@Override
public boolean accept(File dir, String name) {
return name.endsWith(type);// 以Type结尾
}

}
}
 

其中我们用 内部类 的实现,实现了FilenameFilter Interface。所以当我们File list调用接口方法时,传入MyFilter可以让文件名规则按我们想要的获得。

右键 Run 下,可以看到如图所示的输出:

补充:

String[] fs = f.list()

File[] fs = f.listFiles()

String []fs = f.list(FilenameFilter filter);;

File[]fs = f.listFiles(FilenameFilter filter);

三、总结

1、看源码很简单,看怎么用先,在深入看有什么数据结构,设计模式。理理就清楚了

2、学东西,学一点一点深一点。太深不好,一点就够了

3、泥瓦匠学习的代码都在 github 上(同步osc git),欢迎大家点star,提意见,一起进步。地址:

文章来源:智云一二三科技

文章标题:夯实基础:图解 Java IO之FilenameFilter源码

文章地址:https://www.zhihuclub.com/185891.shtml

关于作者: 智云科技

热门文章

发表回复

您的电子邮箱地址不会被公开。

网站地图