【一】需求
查找某个指定目录下,创建日期在指定日期之前,且开头为指定前缀,结尾为指定类型,大小大于指定size的文件。例如:查找我本地磁盘上位于:E:\Other\Picture\私人 目录下,创建日期在2010年1月2日之前,开头为IMG_、DSCN,类型为JPG、GIF,且大小超过2M的图片资源文件。
【二】简介
1.基本功能过滤器
=============================================
①类型:DirectoryFileFilter、FileFileFilter
②大小:EmptyFileFilter、SizeFileFilter
③时间:AgeFileFilter
④名称:NameFileFilter、PrefixFileFilter、SuffixFileFilter、RegexFileFilter、WildcardFileFilter
⑤读写属性:CanReadFileFilter、CanWriteFileFilter
⑥隐藏属性:HiddenFileFilter
2.逻辑关系过滤器
=============================================
①逻辑与:AndFileFilter
②逻辑或:OrFileFilter
③逻辑非:NotFileFilter
④永真/假:TrueFileFilter、FalseFileFilter
3.过滤器容器
=============================================
①工具类:FileFilterUtils
【三】思路
①使用递归方法遍历所有目录
②采用FileFilter定义的各种类型进行组合
具体思路通过阅读代码可以知道
【四】代码
package example.io;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.io.DirectoryWalker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.AgeFileFilter;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.SizeFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
public class ImageFileFilter {
private PrefixFileFilter prefixF;
private SuffixFileFilter suffixF;
private AgeFileFilter ageF;
private SizeFileFilter sizeF;
public static void main(String args[]) {
ImageFileFilter filter = new ImageFileFilter();
// Set cutoff date
Calendar instance = Calendar.getInstance();
instance.set(2010, Calendar.JANUARY, 1, 23, 59, 59);
filter.setFileAge(instance.getTime(), true);
// Set prefix
List<String> prefixs = new ArrayList<String>();
prefixs.add("IMG_");
prefixs.add("DSCN");
filter.setFilePrefix(prefixs);
// Set suffix
List<String> suffixs = new ArrayList<String>();
suffixs.add(".jpg");
suffixs.add(".gif");
filter.setFileSuffix(suffixs);
// Set size
filter.setFileSize(1024 * 1024 * 2);
// Union filter conditions
File baseDir = new File("E:/Other/Picture/私人/");
IOFileFilter fullConditions = new AndFileFilter(filter.unionFilters());
filter.search(baseDir, fullConditions);
}
public void search(File baseDir, FileFilter fullConditions) {
ImageSearcher searcher = new ImageSearcher(baseDir,
(IOFileFilter) fullConditions);
Thread searchThread = new Thread(searcher);
searchThread.start();
try {
searchThread.join(); // child thread join to main thread
} catch (InterruptedException e) {
e.printStackTrace();
}
searcher.displaySearchResult();
}
// ============== Methods to construct kinds of filters ==============
public void setFilePrefix(List<String> prefix) {
prefixF = new PrefixFileFilter(prefix, IOCase.SYSTEM);
}
public void setFileSuffix(List<String> suffix) {
suffixF = new SuffixFileFilter(suffix, IOCase.SYSTEM);
}
public void setFileAge(Date cutoffDate) {
ageF = new AgeFileFilter(cutoffDate);
}
public void setFileAge(Date cutoffDate, boolean acceptOlder) {
ageF = new AgeFileFilter(cutoffDate, acceptOlder);
}
public void setFileSize(long size) {
sizeF = new SizeFileFilter(size);
}
public void setFileSize(long size, boolean acceptLarger) {
sizeF = new SizeFileFilter(size, acceptLarger);
}
private List<FileFilter> unionFilters() {
List<FileFilter> allFilters = new ArrayList<FileFilter>();
allFilters.add(prefixF);
allFilters.add(suffixF);
allFilters.add(ageF);
allFilters.add(sizeF);
return allFilters;
}
// ============ Inner class to do search task ================
class ImageSearcher extends DirectoryWalker implements Runnable {
private volatile boolean cancelled = false;
private File basePath;
private List<String> finalResult = new ArrayList<String>();
private long startTime;
private long endTime;
public ImageSearcher(File basePath, IOFileFilter filter) {
super(FileFilterUtils.directoryFileFilter(), filter, -1);
this.basePath = basePath;
}
public void run() {
filter();
}
public void filter() {
List<String> result = new ArrayList<String>();
try {
startTime = new Date().getTime();
walk(basePath, result);
} catch (IOException e) {
e.printStackTrace();
}
endTime = new Date().getTime();
finalResult = result;
}
public List<String> getResult() {
return finalResult;
}
/** *//**
* Display search result.
*/
public void displaySearchResult() {
String s = null;
System.out.println("\n=======================================");
for (int i = 0; i < finalResult.size(); i++) {
s = (String) finalResult.get(i);
System.out.println(" Image file found: " + s);
}
int size = finalResult.size();
long elapsed = endTime - startTime;
System.out.println("\nFinally found items: " + size);
System.out.println("\nTime costing(ms) on searching: " + elapsed);
System.out.println("=======================================\n");
}
protected boolean handleDirectory(File directory, int depth,
Collection results) throws IOException {
return true;
}
protected void handleFile(File file, int depth, Collection results)
throws IOException {
StringBuffer sb = new StringBuffer(file.getAbsolutePath());
sb.append("------");
sb.append(FileUtils.byteCountToDisplaySize(file.length()));
results.add(sb.toString());
}
public void cancel() {
cancelled = true;
}
protected boolean handleIsCancelled(File file, int depth,
Collection results) {
return cancelled;
}
protected void handleCancelled(File startDirectory, Collection results,
CancelException cancel) {
if (cancelled) {
cancel();
}
System.out.println("\nCancelled by external or interal thread");
finalResult = (List<String>) results;
}
}
}
【四】实验结果
这个目录下有23个子目录,3452张图片
=======================================
... ...
Image file found: E:\Other\Picture\私人\2009-雕塑公园\IMG_4968.JPG------2 MB
Image file found: E:\Other\Picture\私人\2009-雕塑公园\IMG_4977.JPG------3 MB
Image file found: E:\Other\Picture\私人\2009-雕塑公园\IMG_4992.JPG------4 MB
Image file found: E:\Other\Picture\私人\2009-雕塑公园\IMG_5001.JPG------3 MB
Image file found: E:\Other\Picture\私人\2009-雕塑公园\IMG_5010.JPG------2 MB
Finally found items: 1662
Time costing(ms) on searching: 26125
=======================================
-------------------------------------------------------------
生活就像打牌,不是要抓一手好牌,而是要尽力打好一手烂牌。
posted on 2010-04-01 17:52
Paul Lin 阅读(3158)
评论(1) 编辑 收藏 所属分类:
J2SE