2017-02-10 50 views
1

我想從mysql讀取並將結果寫入一個txt文件。正如你所看到的,我使用Apache的Commons IO。結果集包含推文,並且下面的每個SQL查詢幾乎返回725行,以便寫入txt文件。我的問題是寫入速度很慢(每秒2-3kb)。我在這裏錯過了什麼嗎?FileUtils.write寫入速度

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

回答

4

您正在使用,將創建/打開/關閉的每個寫操作的文件(句柄)的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()單個鏡頭到文件系統。

這應該保持新代碼的整體複雜度在合理的水平;但有助於獲得更好的端到端性能。

+1

_你很驚訝,這不會給你最佳的表現?! - - 這個評論並沒有貢獻你的答案。 – OldCurmudgeon

+0

自從我在Java上進行文件操作以來,已經很長時間了,所以現在我看到了noob錯誤。但那個時候使用普通人似乎是合理的。我怎樣才能實施你的建議?有沒有辦法與commons做它,或者我應該使用另一種方法? –

+0

@Aaron Clifton只需使用'FileOutputStream'而不是'File'並使用'IOUtils.write(fos,content,「UTF8」);' – davidxxx