System.out is based around a PrintStream which by default flushes whenever a newline is written.
From the javadoc:
autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the
printlnmethods is invoked, or a newline character or byte ('\n') is written
So the println case you mention is explicitly handled, and the write case with a byte[] is also guaranteed to flush because it falls under "whenever a byte array is written".
If you replace System.out using System.setOut and don't use an autoflushing stream, then you will have to flush it like any other stream.
Library code probably shouldn't be using System.out directly, but if it does, then it should be careful to flush because a library user might override System.out to use a non flushing stream.
Any Java program that writes binary output to System.out should be careful to flush before exit because binary output often does not include a trailing newline.
System.out is based around a PrintStream which by default flushes whenever a newline is written.
From the javadoc:
autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the
printlnmethods is invoked, or a newline character or byte ('\n') is written
So the println case you mention is explicitly handled, and the write case with a byte[] is also guaranteed to flush because it falls under "whenever a byte array is written".
If you replace System.out using System.setOut and don't use an autoflushing stream, then you will have to flush it like any other stream.
Library code probably shouldn't be using System.out directly, but if it does, then it should be careful to flush because a library user might override System.out to use a non flushing stream.
Any Java program that writes binary output to System.out should be careful to flush before exit because binary output often does not include a trailing newline.
When you can't wait for the item to be displayed, flush the stream.
When the JVM goes down, not flushing the stream risks the item being lost in the display buffer, which might make the sensible error message telling you why the JVM went down lost forever. That makes debugging much more difficult, as people then tend to say, "but it didn't get here, because it would have printed this".
java - why we use system.out.flush()? - Stack Overflow
System.out.flush()
Help with Java.io.PrintWriter.flush()? Also a bit of a rant.
java - System.out not flushing - Stack Overflow
When you write data out to a stream, some amount of buffering will occur, and you never know for sure exactly when the last of the data will actually be sent. You might perform many operations on a stream before closing it, and invoking the flush() method guarantees that the last of the data you thought you had already written actually gets out to the file.
Extract from Sun Certified Programmer for Java 6 Exam by Sierra & Bates.
In your example, it doesn't change anything because System.out performs auto-flushing meaning that everytime a byte in written in the buffer, it is automatically flushed.
You use System.out.flush() to write any data stored in the out buffer. Buffers store text up to a point and then write when full. If you terminate a program without flushing a buffer, you could potentially lose data.
So I am confused with the flush() method of the PrintWriter class. According to all documentation descriptions, it 'flushes' the stream, whatever that means. Luckily I got a better explanation somewhere else, but even then it didn't explain how I'd seen it function. GeeksforGeeks said " it means to clear the stream of any element that may be or maybe not inside the stream". Ok, so I assume that just means it empties the stream, yes?
No, that is not what it does. The given code from the GeeksforGeeks website (found here) is as follows:
// Java program to demonstrate
// PrintWriter flush() method
import java.io.*;
class GFG {
public static void main(String[] args)
{
// The string to be written in the Writer
String str = "GeeksForGeeks";
try {
// Create a PrintWriter instance
PrintWriter writer
= new PrintWriter(System.out);
// Write the above string to this writer
// This will put the string in the stream
// till it is printed on the console
writer.write(str);
// Now clear the stream
// using flush() method
writer.flush();
}
catch (Exception e) {
System.out.println(e);
}
}
} With output as follows:
GeeksForGeeks
Simple enough right? Well if you remove line 26 of the code above (writer.flush()) then you get no output. So that means that when you flush the input stream, it actually goes somewhere, it doesn't just get erased. So why isn't that put into the documentation and explanation?
I am upset about this whole thing and I'm annoyed that the official documentation doesn't elaborate more on what 'flush' means in the context of the method, class, etc. But aside from me being upset, I would like someone to either explain whats going on here or to link me to some documentation that actually gets it right.
This sounds a lot like the output isn't being flushed, as its only
System.out.printthat has the trouble.
Typically System.out and System.err are configured differently. (System.err is typically not buffered, and System.out is typically buffered.) However, the javadocs do not specify the flushing behavior of either streams. This could explain the differences in behavior between the (real) console and running in an IDE.
For info, here is how the streams are initialized in Java 8:
FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
setIn0(new BufferedInputStream(fdIn));
setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));
private static PrintStream ewPrintStream(FileOutputStream fos, String enc) {
if (enc != null) {
try {
return new PrintStream(new BufferedOutputStream(fos, 128),
true, enc);
} catch (UnsupportedEncodingException uee) {}
}
return new PrintStream(new BufferedOutputStream(fos, 128), true);
}
As you can see, System.out is initialized as buffered with autoflush enabled.
However, adding
System.out.flush()after the print statement does not cause it to print.
Are you sure about that? A flush() should flush any buffered output.
I suggest that the problem is actually somewhere else; e.g. the print or flush calls are not happening ... for some reason.
It is also possible that some of your problems are due to this:
System.out.print(",\\" + '\n');
As @javaguy points out, a newline character is a platform specific line separator. On some platforms, the console requires something different. The simplest platform independent way to tell the console to do a line break is:
System.out.println(",\\");
Or putting it all together:
System.out.println(",\\");
System.out.print(" " + someString);
System.out.flush(); // This is necessary ... and should work.
Assuming that you are running the program in Windows, the carriage return (
\r) and line feed (\n) together need to be added to print the new line as below:
System.out.print(",\\" + '\r\n');
System.out.print(" " + someString);