[Solved] In Java Where does the PrintWriter write() method write the data [closed]


System.out is a PrintStream, aka an OutputStream, so you’re calling the PrintWriter(OutputStream out) constructor.

It is equivalent to calling the PrintWriter(Writer out) with the following argument:

new BufferedWriter(new OutputStreamWriter(out))

The BufferedWriter is injected for performance reasons.

where is my data buffered?

In the BufferedWriter.

why doesnt “Hello World” get printed

The "Hello World" text is sitting in that buffer, and since you never flush writer, it’ll never be sent downstream to the System.out print stream.

What does it mean to pass System.out as argument to PrintWriter class constructor?

It means that any text written to the PrintWriter will be forwarded to System.out. As the javadoc says: This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.

when i uncomment writer.flush() and writer.close() then also i get the same result.

That is because you already closed System.out, so it will not accept any more output. PrintWriter silently ignores the error thrown when you try. As the javadoc says: Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().


Solution

Calling close() will automatically call flush(), so you don’t need to call flush() before close().

Calling close() on the PrintWriter will automatically call close() on System.out, so you don’t need to do that.

Remove System.out.flush();, System.out.close();, and writer.flush();, and only call writer.close();.

Better yet, you should in general never close System.out, so just call writer.flush();, and leave it open.

3

solved In Java Where does the PrintWriter write() method write the data [closed]