问题
I have a server-client program set that I'm working on and right now I'm having problems with the protocol because the new line at the end of the println statement is confusing the metadata.
In other words, I need to print to a PrintWriter without the new line at the end. I tried just print, but for some reason the other program doesn't get the message that way. I tried, for the sake of experimentation, adding "\n", "\r", and "\n\r" to the end of the statement and it still didn't get any data. Obviously print can't just be print+"\n\r" otherwise I would have gotten the same results using both methods; alas, only one works.
I checked the Javadocs and it says println is, "Prints a String and then terminates the line."
Does anyone know what the difference between these two methods is that might cause such drastically different behavior?
回答1:
From the Javadoc for PrintWriter:
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.
If you're using .print()
you have to manually .flush()
. Simply having \n
or \r\n
in your String
does not do so which is what is causing the different behavior you see.
来源:https://stackoverflow.com/questions/21568028/what-if-the-difference-between-printwriter-print-and-printwriter-println