如果 PrintWriter.print 和 PrintWriter.println 之间的区别呢? [英] What if the difference between PrintWriter.print and PrintWriter.println?

查看:62
本文介绍了如果 PrintWriter.print 和 PrintWriter.println 之间的区别呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在处理的服务器-客户端程序集,现在我遇到了协议问题,因为 println 语句末尾的新行混淆了元数据.

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.

换句话说,我需要打印到 PrintWriter 而不在末尾添加新行.我尝试只打印,但由于某种原因,其他程序没有以这种方式获取消息.为了实验,我尝试在语句的末尾添加\n"、\r"和\n\r",但仍然没有得到任何数据.显然 print 不能只是 print+"\n\r" 否则我会使用这两种方法得到相同的结果;唉,只有一个有效.

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.

我检查了 Javadoc,它说 println 是打印一个字符串然后终止该行."
有谁知道这两种方法之间的区别是什么可能导致如此截然不同的行为?

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?

推荐答案

来自 PrintWriter 的 Javadoc:

From the Javadoc for PrintWriter:

与 PrintStream 类不同,如果启用自动刷新,则仅在调用 println、printf 或 format 方法之一时才会执行,而不是在碰巧输出换行符时执行.这些方法使用平台自己的行分隔符概念,而不是换行符.

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.

如果您使用 .print(),则必须手动 .flush().简单地在 \n\r\n 中包含 String 不会这样做,这就是导致你看到的不同行为.

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.

这篇关于如果 PrintWriter.print 和 PrintWriter.println 之间的区别呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆