【发布时间】:2017-08-13 05:42:48
【问题描述】:
我正在编写一个例程,它将从文件中检索 URL 列表,使用 JSoup 获取每个 URL 的内容,查找特定模式并将结果写入输出文件(每个分析的 URL 一个)。
我有一个 WebPageAnalysisTask(它实现了 Callable),现在它返回 null,但它会返回一个保存处理结果的对象(待完成):
public WebPageAnalyzerTask(String targetUrl, Pattern searchPattern) {
this.targetUrl = targetUrl;
this.searchPattern = searchPattern;
}
@Override
public WebPageAnalysisTaskResult call() throws Exception {
long startTime = System.nanoTime();
String htmlContent = this.getHtmlContentFromUrl();
List<String> resultContent = this.getAnalysisResults(htmlContent);
try (BufferedWriter bw = Files.newBufferedWriter(Paths.get("c:/output", UUID.randomUUID().toString() + ".txt"),
StandardCharsets.UTF_8, StandardOpenOption.WRITE)) {
bw.write(parseListToLine(resultContent));
}
long endTime = System.nanoTime();
return null;
}
我正在使用 NIO 和 try-with-resources 编写文件。
将使用该任务的代码如下:
/**
* Starts the analysis of the Web Pages retrieved from the input text file using the provided pattern.
*/
public void startAnalysis() {
List<String> urlsToBeProcessed = null;
try (Stream<String> stream = Files.lines(Paths.get(this.inputPath))) {
urlsToBeProcessed = stream.collect(Collectors.toList());
if (urlsToBeProcessed != null && urlsToBeProcessed.size() > 0) {
List<Callable<WebPageAnalysisTaskResult>> pageAnalysisTasks = this
.buildPageAnalysisTasksList(urlsToBeProcessed);
ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
List<Future<WebPageAnalysisTaskResult>> results = executor.invokeAll(pageAnalysisTasks);
executor.shutdown();
} else {
throw new NoContentToProcessException();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Builds a list of tasks in which each task will be filled with data required for the analysis processing.
* @param urlsToBeProcessed The list of URLs to be processed.
* @return A list of tasks that must be handled by an executor service for asynchronous processing.
*/
private List<Callable<WebPageAnalysisTaskResult>> buildPageAnalysisTasksList(List<String> urlsToBeProcessed) {
List<Callable<WebPageAnalysisTaskResult>> tasks = new ArrayList<>();
UrlValidator urlValidator = new UrlValidator(ALLOWED_URL_SCHEMES);
urlsToBeProcessed.forEach(urlAddress -> {
if (urlValidator.isValid(urlAddress)) {
tasks.add(new WebPageAnalyzerTask(urlAddress, this.targetPattern));
}
});
return tasks;
}
保存 URL 列表的文件被读取一次。 ExecutorService 为每个 URL 创建任务,并将异步分析和写入结果文件。
现在正在读取文件,并且正在分析每个 URL 的 HTML 内容并将其保存在字符串中。但是,任务不是写入文件。所以我想知道那里会发生什么。
如果我遗漏了什么,有人可以告诉我吗?
提前致谢。
【问题讨论】:
-
你正在用
java.io.BufferedWriter写文件,而不是NIO。
标签: java multithreading nio executorservice callable