You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BlueJ中使用PrintWriter首次有输出后续无输出的原因咨询

问题原因与解决方案

这个现象的核心是BlueJ的JVM复用机制加上你代码里的PrintWriter.close()调用共同导致的,我给你拆解清楚:

为什么第一次运行正常,后续无输出?

  • 你代码里的PrintWriter包装了System.out(标准输出流),而PrintWriter.close()方法执行时,会连带关闭它依赖的底层流——也就是把System.out直接关掉了。
  • BlueJ为了提升运行效率,同一个项目多次运行时会复用同一个JVM进程,而非每次都启动新进程。第一次运行关闭System.out后,后续再运行代码时,System.out已经处于关闭状态,自然没法输出任何内容。

修复方案

有两种简单的解决方式:

方式1:用flush()代替close()

如果你确实需要使用PrintWriter,不要调用close(),改用flush()确保输出立即显示,这样不会关闭底层的System.out:

import java.io.*;
public class test {
    public static void main(String[] args) {
        PrintWriter out= new PrintWriter(System.out);
        out.println(1);
        out.flush(); // 刷新输出缓冲区,不关闭流
        // out.close(); // 注释掉这行,避免关闭System.out
    }
}

方式2:直接使用原生标准输出

你的场景完全不需要额外包装PrintWriter,直接用Java原生的System.out就能解决问题,从根源避免流被误关闭:

public class test {
    public static void main(String[] args) {
        System.out.println(1);
    }
}

内容的提问来源于stack exchange,提问作者Rahil Malhotra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:58:38