通過匿名內部類實現對檔案的過濾
阿新 • • 發佈:2018-12-26
使用FileFileFilter匿名內部類實現對檔案的過濾:
package com.blueZhangTest; import java.io.File; import java.io.FileFilter; public class Demo5 { public static void main(String[] args) { listImages(new File("E:\\gp08\\day09")); } /** * 使用內部類實現對檔案的過濾 對目錄中的結尾是.txt 的檔案進行過濾 * * @param file * 搜尋的目錄 * */ static void listTxt(File file) { File[] files = file.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { String name = pathname.getName(); if (name.endsWith("txt")) { return true; } return false; } }); for (File f : files) { System.out.println(f.getName()); } } /** * 使用內部類實現通過對檔案的過濾 找出file中的img檔案 * * @param file * 表示的是要進行查詢的檔案或者是目錄 * @return 如果是圖片那麼返回true 如果不是的話那麼返回false * @throws RuntimeException * */ static void listImages(File file) { if (!file.isDirectory()) { throw new RuntimeException("指定的路徑不是有效的目錄"); } // 通過匿名內部類實現過濾檔案型別的介面 File[] files = file.listFiles(new FileFilter() { // 如果指定的型別檔案符合,返回true,否則返回false @Override public boolean accept(File pathname) { String fileName = pathname.getName(); // a.bc.jpg // 獲得副檔名 String exName = fileName.substring(fileName.lastIndexOf(".") + 1); // 判斷副檔名的型別 if (exName.equals("jpg") || exName.equals("bmp") || exName.equals("png")) { return true; } return false; } }); int count = 0; for (File f : files) { System.out.println(f.getName()); count++; } System.out.println("共有" + count + "張圖片"); } }