简体   繁体   中英

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

I used reflection like so to print out the properties of the System.out object:

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));
}

This was the result:

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

As you can see, the autoflush is set to false . So my question is simple -- how do I configure System.out to have autoflush set to true ?

Wrap it in another stream:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM