Java I/O之FilenameFilter类列举出指定路径下某个扩展名的文件
这是一个FilenameFilter类用法的例子,实现的列举出“c:\\folder“路径下所有以“.jpg”扩展名的文件。
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package
?com.it161.demo;
?
?import
?java.io.*;
?
?public
?class
?FindCertainExtension?{
?
?????
private
?static
?final
?String?FILE_DIR?=?
"c:\\folder"
;
????
private
?static
?final
?String?FILE_TEXT_EXT?=?
".jpg"
;
?
?????
public
?static
?void
?main(String?args[])?{
????????
new
?FindCertainExtension().listFile(FILE_DIR,?FILE_TEXT_EXT);
????
}
?
?????
public
?void
?listFile(String?folder,?String?ext)?{
?
?????????
GenericExtFilter?filter?=?
new
?GenericExtFilter(ext);
?
?????????
File?dir?=?
new
?File(folder);
?
?????????
if
(dir.isDirectory()==
false
){
????????????
System.out.println(
"Directory?does?not?exists?:?"
?+?FILE_DIR);
????????????
return
;
????????
}
?
?????????
//?list?out?all?the?file?name?and?filter?by?the?extension
????????
String[]?list?=?dir.list(filter);
?
?????????
if
?(list.length?==?
0
)?{
????????????
System.out.println(
"no?files?end?with?:?"
?+?ext);
????????????
return
;
????????
}
?
?????????
for
?(String?file?:?list)?{
????????????
String?temp?=?
new
?StringBuffer(FILE_DIR).append(File.separator)
????????????????????
.append(file).toString();
????????????
System.out.println(
"file?:?"
?+?temp);
????????
}
????
}
?
?????
//?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));
????????
}
????
}
}
如果你想删除这些文件,请看本文Java I/O之用FilenameFilter实现根据文件扩展名删除文件
?
原创文章,转载请注明出处:http://www.it161.com/article/javaDetail?articleid=140111234213
更多原创内容,请访问:http://www.it161.com/