Java - Understanding PrintWriter and need for flush

二次信任 提交于 2019-12-02 01:44:14

The println() methods of the PrintWriter class "commit" the data to the stream only if the autoFlush attribute is enabled.

Look at this quote from the Java docs:

if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked

Link to Java docs here: https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.OutputStream,%20boolean)

If you need to send the message over to the server, then create the PrintWriter object with the autoflush option turned on.

So, where you're creating the writer object, just do this:

writer = new PrintWriter(sock.getOutputStream(), true);

That should do it. Hope it helps!

It's more efficient not to flush the data after every single println. If you're writing a lot of data, you want to buffer it and send in big chunks, not send each line separately. That's why you need to manually flush the streams if you want to make sure that the data is indeed sent to the other end.

Imagine you're writing an email to a friend, and you send each word as its own email vs. sending the whole text in a single email. Which do you think is faster? Sure, your friend will get to read the mail quicker if you send each word as you think of it, but the total time taken will become longer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!