且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果 PrintWriter.print 和 PrintWriter.println 之间的区别呢?

更新时间:2023-12-04 12:18:10

来自 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.