2016-03-02 46 views
1

我試圖將所有JSON結果保存到文本文件中。但是,我的循環似乎只是將循環的最後結果保存到文本文件。顯然,每次將結果重新寫入文件中。我希望能夠在保存文件之前保存for循環的所有結果。如何使用java將所有JSON對象從for循環寫入文本文件

List<Status> statuses = null; 
     Query query = new Query("football"); 
     query.setCount(100); 
     query.lang("en"); 
     int i=0; 





     try {  

       QueryResult result = twitter.search(query); 
       ArrayList tweets = new ArrayList(); 

       for(Status status : result.getTweets()){ 
        System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); 
         String rawJSON = TwitterObjectFactory.getRawJSON(status); 
         String statusfile = "results.txt"; 
         storeJSON(rawJSON, statusfile); 
         i++; 
       } 
       System.out.println(i); 

       } 
       catch(TwitterException e) {   
       System.out.println("Get timeline: " + e + " Status code: " + e.getStatusCode()); 
       }  

    } catch (TwitterException e) { 
     if (e.getErrorCode() == 88) { 
      System.err.println("Rate Limit exceeded!!!!!!"); 
      try { 
       long time = e.getRateLimitStatus().getSecondsUntilReset(); 
       if (time > 0) 
        Thread.sleep(100); 
      } catch (InterruptedException e1) { 
       e1.printStackTrace(); 
      } 
     } 
    } 
} 

private static void storeJSON(String rawJSON, String fileName) throws IOException { 
    FileOutputStream fos = null; 
    OutputStreamWriter osw = null; 
    BufferedWriter bw = null; 
    try { 
     fos = new FileOutputStream(fileName); 
     osw = new OutputStreamWriter(fos, "UTF-8"); 
     bw = new BufferedWriter(osw); 
     bw.write(rawJSON); 
     bw.flush(); 
    } finally { 
     if (bw != null) { 
      try { 
       bw.close(); 
      } catch (IOException ignore) { 
      } 
     } 
     if (osw != null) { 
      try { 
       osw.close(); 
      } catch (IOException ignore) { 
      } 
     } 
     if (fos != null) { 
      try { 
       fos.close(); 
      } catch (IOException ignore) { 
      } 
     } 
    } 
} 

}

在叫storeJSON底部的方法是工作正在緊張進行,其中。

回答

1

你試過用追加模式使用FileWriter嗎?

private static void storeJSON(String rawJSON, String fileName) throws IOException { 
    FileWriter fileWriter = null; 
    try 
    { 
     fileWriter = new FileWriter(fileName, true); 
     fileWriter.write(rawJSON); 
     fileWriter.write("\n"); 
    } 
    catch(IOException ioe) 
    { 
     System.err.println("IOException: " + ioe.getMessage()); 
    } finally { 
     if(fileWriter!=null) { 
      fileWriter.close(); 
     } 
    } 
} 
+0

感謝這工作。 – shah