如何在 java 中使用不同的方法在单个文件中逐行写入

How to Write to line by line in a single file on different methods in java

我想在 java 中写入单个文件,但使用不同的方法。我写了这个

import java.io.*;
public class Test {
  public static File file = new File("text.log");


  public static void main (String [] args) throws IOException
  {
    FileWriter input= new FileWriter(file);
    input.write("hello");
    input.write("\n");
    input.close();
    test();
   }

  public  static void test() throws IOException
   {

    FileWriter input= new FileWriter(file);
    input.write("world");
    input.write("\n");
    input.close();
   }


}

输出只是world。看起来调用函数 test() 会覆盖之前写入的内容。

您需要通过传递 true 作为第二个参数以追加模式打开 FileWriter:

public static File file = new File("text.log", true);

来自Javadoc

public FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

当您写入 new FileWriter(file, true) 时,它将附加而不是覆盖。