Java多线程查找指定文件夹下包含指定关键字的文件数量(未使用线程池版)

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class FutureTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File startingDirectory = new File("F:\\C++ Project");
		String keyWords = "namespace";
		FutureTask<Integer> task = new FutureTask<>(new MatchCounter(startingDirectory, keyWords));
		new Thread(task).start();
		try {
			System.out.println(task.get() + " files match");
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

class MatchCounter implements Callable<Integer> {

	private File directory;
	private String keyWords;
	private int count;

	public MatchCounter(File directory, String keyWords) {
		super();
		this.directory = directory;
		this.keyWords = keyWords;
	}

	@Override
	public Integer call(){
		// TODO Auto-generated method stub
		count = 0;
		List<Future<Integer>> results = new ArrayList<>();
		File[] files = directory.listFiles();
		for(File f : files){
			if(f.isDirectory()){
				MatchCounter match = new MatchCounter(f, keyWords);
				FutureTask<Integer> task = new FutureTask(match);
				results.add(task);
				new Thread(task).start();
			}else{
				try {
					if(search(f)){
						++count;
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		for(Future<Integer> futrue : results){
			try {
				count += futrue.get();
			} catch (InterruptedException | ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return count;
	}
	
	public boolean search(File f) throws FileNotFoundException{
		boolean found = false;
		try(Scanner in = new Scanner(f)){
			while(!found&in.hasNextLine()){
				String line = in.nextLine();
				if(line.contains(keyWords)){
					found = true;
				}
			}
		}
		return found;
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值