如何通过多个类 in Java写入单个文件?

How to write into a single file through multiple classes in Java?

我正在尝试通过不同的 classes 写入单个文本文件。 我从主 class:

打开文本文件
public static void main( String[] args ) throws Exception {
    BufferedWriter writer = new BufferedWriter(new FileWriter("src/t1.txt"));
    Parser.getParseTree().print(); // where I called the method
    writer.close();
  }

这是另一个 class:

的 print() 方法
    public static  void print() throws IOException {

            BufferedWriter writer = new BufferedWriter(new FileWriter("src/t1.txt"));
            writer.write("afcad fad fad");
     }

BufferedWriter writer = new BufferedWriter(new FileWriter("src/t1.txt"));in print() 方法不起作用,没有任何内容打印到 t1.txt 文件。

不要有多个地方(方法)各自写入文件。

只需使用一个打开文件进行写入的中心位置(可能使用 try-with-resource)并让任何其他代码在该中心位置调用方法。换句话说,您所有的代码都应该只调用相同的方法!