gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:01:52 31 4
gpt4 key购买 nike

我正在尝试将 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 的方法是完成工作的地方。

最佳答案

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

关于java - 如何使用 java 将 for 循环中的所有 JSON 对象写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35750610/

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