在Java中多次执行同一程序时,写入同一文件

时间:2019-04-22 04:53:09

标签: java

我有以下代码, 它所做的是,它从http连接获取响应并将其写入logs.txt。 当我执行程序时,响应将写入txt文件,但是当我再次运行同一程序时,它不会将响应写入txt文件。

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                BufferedWriter out = new BufferedWriter(new FileWriter("C:/Users/mkumaru/Desktop/Elastic/elasticsearch/server/logs/logs.txt"));
                try {
                    out.write(response.toString());
                }
                catch (IOException e)
                {
                    System.out.println("Exception ");
                }
                finally
                {
                    out.close();
                }

所以我期望的是, 在第一次执行时,logs.txt应该是 response1

在同一程序的第二次执行中, 回应1 response2

我该怎么做。

1 个答案:

答案 0 :(得分:0)

BufferedWriter writer = new BufferedWriter(
                            new FileWriter("C:/Users/mkumaru/Desktop/Elastic/elasticsearch/server/logs/logs.txt", true)  //Set true for append mode
                        ); 
writer.newLine();   //Add new line
writer.write(textToAppend);