PrintStream和PrintWriter的源码理解

本文深入探讨了PrintStream类的功能及其内部实现机制,重点介绍了如何进行自动flush操作,并解释了在何种情况下会触发自动flush。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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')
废话不说,分析源码:



















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值