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;
}
}
Java多线程查找指定文件夹下包含指定关键字的文件数量(未使用线程池版)
最新推荐文章于 2023-06-26 14:59:27 发布