在Java中,你可以實現了 FilenameFilter,重寫accept(File dir, String name)方法,執行該文件過濾功能。
在這個例子中,我們將向您展示如何使用FilenameFilter,列出的都是文件夾“c:\\folder” 裡所有文件擴展名以“.txt” 結束的文件,然後將其刪除。
package com.yiibai.io; import java.io.*; public class FileChecker { private static final String FILE_DIR = "c:\\folder"; private static final String FILE_TEXT_EXT = ".txt"; public static void main(String args[]) { new FileChecker().deleteFile(FILE_DIR,FILE_TEXT_EXT); } public void deleteFile(String folder, String ext){ GenericExtFilter filter = new GenericExtFilter(ext); File dir = new File(folder); //list out all the file name with .txt extension String[] list = dir.list(filter); if (list.length == 0) return; File fileDelete; for (String file : list){ String temp = new StringBuffer(FILE_DIR) .append(File.separator) .append(file).toString(); fileDelete = new File(temp); boolean isdeleted = fileDelete.delete(); System.out.println("file : " + temp + " is deleted : " + isdeleted); } } //inner class, generic extension filter public class GenericExtFilter implements FilenameFilter { private String ext; public GenericExtFilter(String ext) { this.ext = ext; } public boolean accept(File dir, String name) { return (name.endsWith(ext)); } } }