两个 PrintWriter 对象只打印一次

Two PrintWriter objects printing only once

我有以下代码片段。代码看起来不错,但是无法在屏幕上打印 Bye

import java.io.PrintWriter;

public class PrintWriterTwice {
  public static void main(String[] args) {
    PrintWriter first = new PrintWriter(System.out);
    first.print("Hello");
    first.flush();
    first.close();

    PrintWriter second = new PrintWriter(System.out);
    second.print("Bye");
    second.flush();
    second.close();
  }
}

程序的输出如下:

Hello

请问我为什么会出现这种行为?

PrintWriter 上调用 close() 关闭基础 OutputStream(在本例中为 System.out);所以你没有进一步的输出。删除 close() - 或将其移至 second 写入后。

PrintWriter first = new PrintWriter(System.out);
first.print("Hello");
first.flush();

PrintWriter second = new PrintWriter(System.out);
second.print("Bye");
second.flush();
first.close();
second.close();