Java I/O之用FilenameFilter实现根据文件扩展名删除文件
在Java中,你可以通过实现FilenameFilter类并重写accept(File dir, String name) 方法实现文件过滤功能。
在这个例子中,我们向你展示在“c:\\folder”路径下列出所有“.txt”格式的文件并删除。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849package
?com.it161.demo;
?
?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));
???????
}
????
}
}
?
原创文章,转载请注明出处:http://www.it161.com/article/javaDetail?articleid=140111233238
更多原创内容,请访问:http://www.it161.com/
?