圖解 Java IO : 二、FilenameFilter原始碼
Writer :李強強
從上一篇 圖解 Java IO : 一、File原始碼 並沒有把所有File的東西講完。這次講講FilenameFilter,關於過濾器檔案《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 * * http://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
Writer :BYSocket(泥沙磚瓦漿木匠)