使用BlockingQueue查詢某個資料夾下的所有文字檔案中是否包含文字
阿新 • • 發佈:2019-01-03
阻塞佇列的使用:
public class FileCrawler implements Runnable {
private final BlockingQueue<File> fileQueue = new LinkedBlockingQueue<>(10);
final List<String> result = new ArrayList<>(16);
private final FileFilter filter;
private final String root;
volatile boolean running = true;
private Indexer indexer;
public FileCrawler(FileFilter filter, String root) {
this.filter = filter;
this.root = root;
indexer = new Indexer("Indexer");
}
@Override
public void run() {
File src = new File(root);
if (src.exists()) {
try {
indexer.start();
cralw(src);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
running = false;
}
private void cralw(File src) throws InterruptedException {
File[] files = src.listFiles();
if (files != null)
for (File file : files) {
if (file.isDirectory())
cralw(file);
else if (filter.accept(file))
fileQueue.put(file);
}
}
private class Indexer extends Thread {
public Indexer(String name) {
super(name);
}
@Override
public void run() {
while (running || !fileQueue.isEmpty()) {
try {
indexFile(fileQueue.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
showResult();
}
private void indexFile(File take) {
LineNumberReader in = null;
try {
in = new LineNumberReader(new FileReader(take));
String line;
while ((line = in.readLine()) != null) {
if (line.contains("it")) {
addResult(in, take, line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void addResult(LineNumberReader in, File src, String line) {
StringBuilder msg = new StringBuilder();
String path = src.getAbsolutePath();
msg.append("path : " + path + " ; ");
msg.append("lineNumber : " + in.getLineNumber() + " ; ");
msg.append("line : " + line);
result.add(msg.toString());
}
}
public void showResult() {
for (String str : result) {
System.out.println(str);
}
}
}
呼叫
public class TestFindTxt {
public static void main(String[] args) {
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".txt");
}
};
String root = "g:/a";
FileCrawler crawler = new FileCrawler(filter, root);
new Thread(crawler).start();
}
}
結果: