首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileUtils.write写入速度

FileUtils.write写入速度
EN

Stack Overflow用户
提问于 2017-02-10 12:33:31
回答 1查看 1.3K关注 0票数 1

我正在尝试从mysql读取并将结果写入txt文件。如您所见,我使用Apache的Commons。结果集包含tweet,下面的每个sql查询几乎返回725行要写入txt文件。我的问题是写入速度很慢(每秒2-3kb).我是不是漏掉了什么?

代码语言:javascript
复制
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++;
            }
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-10 12:38:01

您正在使用一个API,它将为每个写操作创建/打开/关闭一个文件(句柄)。

你很惊讶这没有给你最佳的表现?!

这种实用方法可能很方便,但见鬼,而不是去

代码语言:javascript
复制
loop:
  try:
    open file; write to file; close file
    open file; write to file; close file

考虑按…的方式做某事

代码语言:javascript
复制
open file
loop:
  try:
    write to open file
    write to open file
close file

而不是。当然,这意味着您必须编写更多的代码;使事情变得更加复杂;但是,我们必须在“超级容易读”的代码与“执行足够好的”代码之间取得平衡。

最可能的返工方式可能是这样的:

代码语言:javascript
复制
StringBuilder toWrite = ...
loop:
  try:
  toWrite.append(...)
  toWrite.append(...)

然后,在循环之后,您使用FileUtils.write(),以便将整个内容(您在内存中收集到的)在一个中一次写入文件系统。

这将使您的新代码的总体复杂性保持在一个合理的水平上,但有助于提高端到端的性能。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42159519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档