What if the difference between PrintWriter.print and PrintWriter.println?

给你一囗甜甜゛ 提交于 2019-12-20 07:09:01

问题


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

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