圖解 Java IO : 二、FilenameFilter源碼,iofilenamefilter
Writer :BYSocket(泥沙磚瓦漿木匠)
微 博:BYSocket
豆 瓣:BYSocket
FaceBook:BYSocket
Twitter :BYSocket
從上一篇 圖解 Java IO : 一、File源碼 並沒有把所有File的東西講完。這次講講FilenameFilter,關於過濾器檔案《Think In Java》中寫道:
更具體地說,這是一個策略模式的例子,因為list()實現了準系統,而按著形式提供了這個策略,完善list()提供服務所需的演算法。
java.io.FilenameFilter是檔案名稱過濾器介面,即過濾出符合規則的檔案名稱組。
一、FilenameFilter源碼
從IO的UML可以看出,FilenameFilter介面獨立,而且沒有它的實作類別。下面就看看它的源碼:
?
| 123456789 |
publicinterface FilenameFilter { /** * 測試指定檔案是否應該包含在某一檔案清單中。 * * @param 被找到的檔案所在的目錄。 * @param 檔案的名稱 */ booleanaccept(File dir, String name);} |
從JDK1.0就存在了,功能也很簡單:就是為了過濾檔案名稱。只要在accept()方法中傳入相應的目錄和檔案名稱即可。
深度分析:介面要有真正的實現才能算行為模式中真正實現。所以這裡使用的是策略模式,涉及到三個角色:
環境(Context)角色
抽象策略(Strategy)角色
具體策略(Context Strategy)角色
結構圖如下:
其中,FilenameFiler Interface 就是這裡的抽象策略角色。其實也可以用抽象類別實現。
二、使用方法
FilenameFiler使用。上代碼吧:(small 廣告是要的,代碼都在 開源項目java-core-learning。地址:https://github.com/JeffLi1993)
?
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
packageorg.javacore.io; importjava.io.File;importjava.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); } } /** * 內部類實現過濾器檔案介面 */ staticclass MyFilter implementsFilenameFilter { privateString type; publicMyFilter (String type) { this.type = type; } @Override publicboolean accept(File dir, String name) { returnname.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(泥沙磚瓦漿木匠)
微 博:BYSocket
豆 瓣:BYSocket
FaceBook:BYSocket
Twitter :BYSocket
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。