我正在尝试从mysql读取并将结果写入txt文件。如您所见,我使用Apache的Commons。结果集包含tweet,下面的每个sql查询几乎返回725行要写入txt文件。我的问题是写入速度很慢(每秒2-3kb).我是不是漏掉了什么?
Statement stmt2 = connection.createStatement();
for (int week = 0 ; week<hashTag.length/15 ; week++){
File container = new File("C:\\Users\\COMP\\Desktop\\threeMonthsSplitTxt\\weeklyBinsTwitter\\week"+week+"-"+hashTag[week]+".txt");
for(int hash = 0 ; hash<15 ; hash++){
ResultSet results = stmt2.executeQuery("select tweetContent
from threemonthswithhashtag
where hashTag = '"+hashTag[hashCount]+"'
and tweetCreatedTime between '"+firstDate[hashCount]+"'
and '"+ lastDate[hashCount]+"';");
while(results.next()){
tweetContent = results.getString("tweetContent");
try{
FileUtils.write(container,newLine,"UTF8",true);
FileUtils.write(container,tweetContent,"UTF8",true);
}catch(IOException e){e.getMessage();}
}
hashCount++;
}
}发布于 2017-02-10 12:38:01
您正在使用一个API,它将为每个写操作创建/打开/关闭一个文件(句柄)。
你很惊讶这没有给你最佳的表现?!
这种实用方法可能很方便,但见鬼,而不是去
loop:
try:
open file; write to file; close file
open file; write to file; close file考虑按…的方式做某事
open file
loop:
try:
write to open file
write to open file
close file而不是。当然,这意味着您必须编写更多的代码;使事情变得更加复杂;但是,我们必须在“超级容易读”的代码与“执行足够好的”代码之间取得平衡。
最可能的返工方式可能是这样的:
StringBuilder toWrite = ...
loop:
try:
toWrite.append(...)
toWrite.append(...)然后,在循环之后,您使用FileUtils.write(),以便将整个内容(您在内存中收集到的)在一个中一次写入文件系统。
这将使您的新代码的总体复杂性保持在一个合理的水平上,但有助于提高端到端的性能。
https://stackoverflow.com/questions/42159519
复制相似问题