PrintStream与PrintWriter的区别

        有一天在进行网络编程的练习时,发现如果使用PrintStream进行输出,可以不用指定手动刷新或者设置自动刷新即可完成输出,而PrintWriter则不同,一定要在构造方法中设置自动刷新或者在调用println()方法以后再调用flush(),才可以立即完成输出。

       比较一下PrintStream与PrintWriter的区别:

            PrintStream主要操作字节流,也就是说打印出来所有字符按照平台的编码转换为字节,所以一般用于二进制文件。(文本文件也是可以的)

               字符串转换为字节流是平台相关的,也就是说 不同的系统或者环境,可能对于同一份字符串的输出字节流会有差异

不能够跨平台。

            PrintWriter主要操作字符,可以创建指定的字符集,一般用来读取文本文件,因为默认用unicode编码,所以PrintWriter的跨平台性要比PrintStream好,也就是说PrintWriter可用于操作中文。

           在自动刷新方面,

          PrintStream在遇到换行符的时候就会自动刷新,即在调用了println()方法,或者文本中出现“\n”,就会自动flush

          PrintWriter则不会,要在构造方法中设置自动刷新,或者手动flush。


翻译自:

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 PrintWriter class should be used in situations that require writing characters rather than bytes.

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/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值