PrintStream和PrintWriter的源码理解
1.PrintStream
A PrintStream adds functionality to another output stream ,namely the ablity to print representations of various data coventiontly . Two other features are provided as well . unlike other output streams , a PrintStream never throws an IOException ; Instead
, exceptional situations merely set an internal flag that can be tested via the checkError method . Optionally , 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 by the platform's default character encoding . the PrintWriter class should be used in the situations that require writing characters rather than bytes.
说明几点:
- PrintStream在另一个输出流上面添加了功能,比如方便的打印不同形式的数据
- 其他功能:能够自动flush,从不产生异常
- PrintStream只是设置了一个内部标识,当PrintStream出错时,将标识置为true ,这个能通过方法checkError检测出来
- 用平台相关编码将字符转换成字节
- 什么情况下自动flush: 1)当写”字节数组“的时候
- 2)当任何一个println方法被调用的时候
- 3)写一个换行符(newline character)
- 4) 写的string里面有换行符(byte '\n')