圖解 Java IO : 二、FilenameFilter源碼
更具體地說,這是一個策略模式的例子,因為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。地址:https://github.com/JeffLi1993)
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 * * https://www.apache.org/licenses/LICENSE-2.0 * * 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,提意見,一起進步。地址:https://github.com/JeffLi1993
最後更新:2017-05-22 15:32:49