利用Callable,统计目录下有多少个文件中包含指定的关键字

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class FutureTest {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("Enter base directory (C:/Program Files/Java/jdk1.7.0/src):");
		String directory = in.nextLine();
		System.out.print("Enter keyword (java):");
		String keyword = in.nextLine();
		
		MatchCounter counter = new MatchCounter(new File(directory), keyword);
		FutureTask<Integer> task = new FutureTask<Integer>(counter);
		Thread t = new Thread(task);
		t.start();
		
		try {
			System.out.println(task.get() + " matching files.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


class MatchCounter implements Callable<Integer> {

	public MatchCounter(File directory, String keyword) {
		this.directory = directory;
		this.keyword = keyword;
	}
	
	@Override
	public Integer call() throws Exception {
		count = 0;
		
		try {
			File[] files = directory.listFiles();
			ArrayList<FutureTask<Integer>> results = new ArrayList<FutureTask<Integer>>();
			
			for(File file : files) {
				if(file.isDirectory()) {
					//再为每一个目录在启动一个线程
					MatchCounter counter = new MatchCounter(file, keyword);
					FutureTask<Integer> task = new FutureTask<Integer>(counter);
					results.add(task);
					
					Thread t = new Thread(task);
					t.start();
				} else {
					if(search(file)) {
						count++;
					}
				}
			}
			
			//把文件遍历完后,再对匹配的文件个数进行统计
			for(FutureTask<Integer> result : results) {
				count += result.get();
			}
		} catch (Exception e) {
		}
		
		return count;
	}
	
	private boolean search(File file) {
		try {
			Scanner in = new Scanner(new FileInputStream(file));
			boolean found = false;
			//找到有关键字,返回true
			while(!found && in.hasNextLine()) {
				String line = in.nextLine();
				if(line.contains(keyword)) {
					found = true;
				}
			}
			in.close();
			return found;
		} catch (Exception e) {
			return false;
		}
	}
	
	private int count;
	private File directory;
	private String keyword;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值