首页 > 代码库 > 从指定的路径中查找含有特殊字符串的文件
从指定的路径中查找含有特殊字符串的文件
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
public class SearchFile
{
public static void main(String ... strings)
{
final int FILE_Queue_SIZE = 10;
final int SEARCH_THREADS = 100;
Scanner in = new Scanner(System.in);
System.out.println("enter your base directory:");
String directory = in.nextLine();
System.out.println("enter your keyword");
String keyword = in.nextLine();
ExecutorService pool= Executors.newCachedThreadPool();
MatchCounter counter = new MatchCounter(new File(directory),keyword,pool);
Future<Integer> result = pool.submit(counter);
try
{
System.out.println("result.get()=" + result.get() + "matching files.");
}
catch (Exception e)
{
e.printStackTrace();
}
pool.shutdown();
int largestPoolSize = ((ThreadPoolExecutor)pool).getLargestPoolSize();
System.out.println("largestPoolSize=" + largestPoolSize);
}
}
class MatchCounter implements Callable<Integer>
{
private File directory;
private String keyword;
private ExecutorService pool;
private int count;
public MatchCounter(File directory, String keyword, ExecutorService pool)
{
this.directory = directory;
this.keyword = keyword;
this.pool = pool;
}
public Integer call()
{
count = 0;
try
{
File[] files = directory.listFiles();
ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();
for(File file:files)
{
if(file.isDirectory())
{
MatchCounter counter = new MatchCounter(file,keyword,pool);;
Future<Integer> result = pool.submit(counter);
results.add(result);
}else
{
if (search(file))
{
count++;
System.out.println("路径:" + file.getAbsolutePath());
}
}
}
for(Future<Integer> result:results)
{
try
{
count += result.get();
System.out.println("count=" + count + "-----" + "result.get()=" + result.get());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}catch (Exception e)
{
e.printStackTrace();
}
return count;
}
public boolean search(File file)
{
try
{
Scanner in = new Scanner(new FileInputStream(file));
boolean found = false;
while(!found && in.hasNextLine())
{
String line = in.nextLine();
if(line.contains(keyword)) found = true;
}
in.close();
return found;
}
catch (Exception e)
{
return false;
}
}
}