gpt4 book ai didi

java - FileUtils.write写入速度

转载 作者:行者123 更新时间:2023-11-29 04:35:53 24 4
gpt4 key购买 nike

我正在尝试从 mysql 读取并将结果写入 txt 文件。如您所见,我使用 Apache 的 Commons IO。结果集包含推文,下面的每个 sql 查询几乎返回 725 行以写入 txt 文件。我的问题是写入速度,它非常慢(每秒 2-3 kb)。我在这里遗漏了什么吗?

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++;
}
}

最佳答案

您使用的 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

相反。当然,这意味着您将不得不编写更多 代码;让事情变得更复杂;但好吧:有时必须在“ super 容易阅读”的代码与“性能足够好”的代码之间取得平衡。

可能最多的返工甚至会像这样:

StringBuilder toWrite = ...
loop:
try:
toWrite.append(...)
toWrite.append(...)

然后,在循环之后,您使用 FileUtils.write() 来简单地一次写入全部内容(您在内存中收集的内容)到文件系统。

这应该使新代码的整体复杂性保持在合理的水平;但有助于提高端到端性能。

关于java - FileUtils.write写入速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42159519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com