3

私は Java を初めて使用し、いくつかのオープン ソース コードを組み合わせてツイートを検索しようとしてきましたが、ついに成功することができました。次に、出力をテキスト ファイルに保存したいと考えました。コンソール出力メソッド、ファイルライター、プリントライターを検索して確認しましたが、ここで機能するものを見つけましたが、保存するツイートは1つだけで、保存した以前のツイートを上書きします. 以前の保存を上書きせずに既存のテキスト ファイルを適切に追加し、コンソール画面からすべてのツイートを確実に保存するにはどうすればよいですか? 以下のコード例:

    JSONObject js = new JSONObject(buff.toString());  
    JSONArray tweets = js.getJSONArray("results");  
    JSONObject tweet;  
    for(int i=0;i<tweets.length();i++) {  
        tweet = tweets.getJSONObject(i); 
        PrintWriter out;
         try {
        out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt"));
        System.out.println((i+1)+")http://twitter.com/"+tweet.getString("from_user")+" at "+tweet.getString("created_at"));  
        System.out.println(tweets.getJSONObject(i).getString("text")+"\n");
        out.println((i+1)+")http://twitter.com/"+tweet.getString("from_user")+" at "+tweet.getString("created_at"));
        out.println(tweets.getJSONObject(i).getString("text")+"\n");

         out.close();
    } catch (IOException e) {
        e.printStackTrace();
    } 


}

} }

4

4 に答える 4

5

あなたはとても興味をそそるほど近くにいます。FileWriterappend を に設定してを開くだけですtrue。Append は、毎回上書きするのではなく、ファイルの最後に追加します。

out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt", true));
于 2013-05-28T01:52:14.723 に答える
1

の各反復中にオブジェクトPrintWriterとオブジェクトを作成する代わりに、PrintWriterを外部で初期化して(パフォーマンスが向上します)、最後にリソースを解放する必要があります。FileWriterfor loopfor loop

PrintWriter  out = null ;
try
{
  // putting
  out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt"),true); // appending file if exists.
  // JSON Parsing instructions
  for(int i=0;i<tweets.length();i++) 
  { 
    // processing logic and write operation to file
  }
}
catch(CustomExceptions e) {//All other exception handling}
catch(Exception e){//Generic exception handling }
finally{
          if(out != null
          {
              out.close();
          }
       }
于 2013-05-28T02:28:15.630 に答える
1

この行を変更します (以前に書き込まれたデータが消去されるため):

out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt"));

For (ここでは Append モードを true に設定しています)

out = new PrintWriter(new FileWriter("C:\\tweet\\outputfile.txt"), true);

デフォルト モードは false に設定されているため、ファイルが上書きされます。

于 2013-05-28T01:53:38.213 に答える
-1

public final String path="あなたのパス"

        PrintWriter pw = new PrintWriter(new FileWriter(path),true);/*automatically append the line you want to save and if false it will overwrite the data */

pw.write("あなたが望むものは何でも")

        pw.close();
于 2015-05-07T09:43:11.453 に答える