我正在将解析网页的输出写入两个文本文件。 “CrawledURLS.txt”保存已抓取的页面,“CrawledURLSERROR.txt”保存未抓取的网页。由于我应该获得一些输出数据图,因此我将 .txt 文件转换为 .xls 文件。我收到超过“300.000”的 URL。当我停止程序检查输出时,我发现某些列向右移动或包含不正确的信息。
这是我编写输出的地方:
LinkNode deque(){
LinkNode link = pQUEUE.poll();
link.setDequeTime(new DateTime());
for (LinkNode l : pQUEUE) {
DateTime start = new DateTime();
l.setDequeTime(start);
l.setStartTime(start);
PingTaskManager.ping(l);
if(l.getStatus()!= null && l.getStatus().equals(LinkNodeStatus.OK)) {
try (PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter("CrawledURLS.txt",true)))){
l.setEndTime(new DateTime());
out.println( l.getUrl() + ": "+ l.getWeight() + " InTime: "+
Util.formatDate(l.getDequeTime()) + " OutTime: " + Util.formatDate(l.getEnqueTime())+" Waiting duration :" + l.waitingInQueue()
+ " Processing duration :" + l.linkProcessingDuration() );
} catch(IOException e){
}
} else {
try (PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter("CrawledURLSERROR.txt",true)))){
l.setEndTime(new DateTime());
out.println( l.getUrl() + ": "+ l.getWeight() + " InTime : "+
Util.formatDate(l.getDequeTime()) + " OutTime : " + Util.formatDate(l.getEnqueTime())+" Waiting duration :" + l.waitingInQueue()
+ " Processing duration :" + l.linkProcessingDuration() );
} catch(IOException e){
}
}
}
return link;
}
这是我得到的输出:
关于这个问题我有两个问题:
1- 为什么会发生这种腐败?
2- 如何将代码转换为使用 .csv 文件而不是 .txt 输出?这能解决问题吗?
最佳答案
很有可能编写 CSV 文件可以解决此问题,因为问题似乎是 Excel 猜测如何将文本数据放入列中。
请注意,CSV 不是标准。不同程序的 CSV 格式有所不同,例如如何进行引用以及是否可以引用换行符。
因此,请使用经过调试的 CSV 库,例如 Apache 库 https://commons.apache.org/proper/commons-csv/并将其设置为向 Excel 写入数据。
此外,不要在每个输出行(重新)打开一次输出文件。这可能会导致问题,而且速度肯定会很慢。相反,打开两个输出文件,向每个文件写入标题行(给出列名称),然后循环数据,添加数据值行,最后关闭文件。
(如果 CSV 引用不足以满足您的数据,您可以切换到定义明确的标准,例如 JSON 或 XML。)
关于java - 为什么在将文本转换为 java 中的 xls 文件后写入文本时,输出会发生移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409022/