有一天在进行网络编程的练习时,发现如果使用PrintStream进行输出,可以不用指定手动刷新或者设置自动刷新即可完成输出,而PrintWriter则不同,一定要在构造方法中设置自动刷新或者在调用println()方法以后再调用flush(),才可以立即完成输出。
比较一下PrintStream与PrintWriter的区别:
PrintStream主要操作字节流,也就是说打印出来所有字符按照平台的编码转换为字节,所以一般用于二进制文件。(文本文件也是可以的)
字符串转换为字节流是平台相关的,也就是说 不同的系统或者环境,可能对于同一份字符串的输出字节流会有差异
不能够跨平台。
PrintWriter主要操作字符,可以创建指定的字符集,一般用来读取文本文件,因为默认用unicode编码,所以PrintWriter的跨平台性要比PrintStream好,也就是说PrintWriter可用于操作中文。
在自动刷新方面,
PrintStream在遇到换行符的时候就会自动刷新,即在调用了println()方法,或者文本中出现“\n”,就会自动flush
PrintWriter则不会,要在构造方法中设置自动刷新,或者手动flush。
翻译自:
a PrintStream
can be created so as to flush automatically; this means that the flush
method is automatically invoked after a byte array is written, one of the println
methods is invoked, or a newline character or byte ('\n'
) is written.
All characters printed by a PrintStream
are converted into bytes using the platform's default character encoding. The
class should be used in situations that require writing characters rather than bytes.PrintWriter
printWriter:
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println() methods is invoked, rather than whenever a newline character happens to be output. The println() methods use the platform's own notion of line separator rather than the newline character.
Methods in this class never throw I/O exceptions. The client may inquire as to whether any errors have occurred by invoking checkError().
参考:http://blog.csdn.net/y3wegy/article/details/8783314
http://121dog198.blog.163.com/blog/static/508599502012103033241629/