2

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?

Dasmowenator
  • 5,505
  • 5
  • 36
  • 50
  • 3
    What jvm are you using? I receive autoFlush = true, which is consistent with OpenJDK source code, both for Java 8 and Java 11. For Java11 check: https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/lang/System.java#L1968 and https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/lang/System.java#L1886 – Lesiak Jan 29 '20 at 21:26

2 Answers2

5

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);
nylanderDev
  • 531
  • 4
  • 14
-1

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

JuanMoreno
  • 2,498
  • 1
  • 25
  • 34