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; }
利用Callable,统计目录下有多少个文件中包含指定的关键字
最新推荐文章于 2020-04-19 21:17:47 发布