如何使用java将所有JSON对象从for循环写入文本文件

时间:2016-03-02 14:52:59

标签: java json for-loop text-files

我正在尝试将我的所有结果从JSON保存到文本文件中。但是,我的for循环似乎只是将循环的最后结果保存到文本文件中。显然,每次只是将结果重写到文件中。我希望能够在保存文件之前保存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 个答案:

答案 0 :(得分:2)

您是否尝试过使用附加模式的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();
        }
    }
}