I was following this tutorial (dateserver) on Socket programming in Java:
http://cs.lmu.edu/~ray/notes/javanetexamples/
This is the piece of code i don't understand:
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
}
What is PrintWriter doing here? why we need to set the parameter to 'true?' i guess first we enable outputstream for the socket (by making it true
) and then with the out.println
we send date as outputstream, is my assumption right?
What is
PrintWriter
doing here? why we need to set the parameter to 'true?' i guess first we enable outputstream for the socket (by making it true) and then with the out.println we send date as outputstream, is my assumption right?
Your assumption is wrong. Read more about it below.
new PrintWriter(socket.getOutputStream(), true);
What JavaDoc of PrintWriter states:
Creates a new
PrintWriter
from an existingOutputStream
. This convenience constructor creates the necessary intermediateOutputStreamWriter
, which will convert characters into bytes using the default character encoding.
Here PrintWriter
stream is connected to the client/server's output stream it means any data written by print writer will sent to client/server.
Here true
means Auto-flush the data from the output buffer once new line methods are called such as println()
, printf()
, or format()
or any newline character ('\\n') is found in the string. In that case you don't need to call flush()
method manually.
From the Javadocs, the PrintWriter
class "prints formatted representations of objects to a text-output stream". In this case it is printing the date to the output stream attached to the socket.
true
in the constructor means subsequent call to out.println(new Date().toString())
will automatically flush the buffer of the output stream, meaning it will force the string to be written to the stream, instead of storing the string in a temporary buffer.
创建PrintWriter对象以写入OutputStream对象,true用于刷新流,请在以下API中检查构造函数: http : //docs.oracle.com/javase/7/docs/api/java/io/ PrintWriter.html
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.