Java: 如何配置 System.out 以启用自动刷新?

Java: How to configure System.out to have autoflush enabled?

我像这样使用反射来打印出 System.out 对象的属性:

System.out.println("Class: " + System.out.getClass().getName());
for (Field field : ObjectUtils.getAllFields(System.out)) {
    field.setAccessible(true);
    System.out.println("> " + field.getType().getSimpleName() + ' ' + field.getName() + " = " + field.get(System.out));
}

这是结果:

Class: java.io.PrintStream
> boolean autoFlush = false
> boolean trouble = false
> Formatter formatter = null
> BufferedWriter textOut = java.io.BufferedWriter@43c1b556
> OutputStreamWriter charOut = java.io.OutputStreamWriter@587e5365
> boolean closing = false
> OutputStream out = org.apache.tools.ant.util.TeeOutputStream@22fcf7ab

如您所见,autoflush 设置为 false。所以我的问题很简单——如何配置 System.out 以将 autoflush 设置为 true

将其包装在另一个流中:

PrintStream newOut = new PrintStream(System.out, true);
// And then set it to out (Credit to David Zimmerman in the comments)
System.setOut(newOut);

System.out.println() execute System.out.flush()

之后