为了过滤以(.txt)为扩展名的文件,本例实现了FilenameFilter类,及其方法
accept(File dir, String name).
本例会删除N:\\eclipse\\workspace\\JavaIO目录下的所有文本文件。
完整例子如下:
- package org.hnrsc.io;
-
-
import java.io.File;
-
import java.io.FilenameFilter;
- public class FileChecker {
-
-
private static final String FILE_DIR = "N:\\eclipse\\workspace\\JavaIO";
-
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 ext
-
String[] list = dir.list();
-
-
if(list.length == 0){
-
return;
-
}
-
File fileDelete;
-
-
for(String filename : list){
-
String temp = new StringBuffer(FILE_DIR).append(File.separator).append(filename).toString();
-
fileDelete = new File(temp);
-
boolean isdeleted = fileDelete.delete();
-
System.out.println("File: "+ temp + " is deleted: " + isdeleted);
-
}
-
}
-
-
//inner class , generic extention filter
-
public class GenericExtFilter implements FilenameFilter{
-
private String ext;
-
-
public GenericExtFilter(String ext){
-
this.ext = ext;
-
}
-
-
@Override
-
public boolean accept(File dir, String name) {
-
return (name.endsWith(ext));
-
}
-
-
}
-
-
}
阅读(2492) | 评论(1) | 转发(0) |