PrintStream和PrintWriter的源码理解

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



















阅读更多

PrintStreamPrintWriter究竟有什么不同?

02-28

找到一些文档,但英文我不很明白:rnpublic class PrintWriter extends Writer rnPrint formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams. rnUnlike 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. rnrnMethods in this class never throw I/O exceptions. The client may inquire as to whether any errors have occurred by invoking checkError(). rn———————————————————————————————————————rnpublic class PrintStream extends FilterOutputStream rnPrint values and objects to an output stream, using the platform's default character encoding to convert characters into bytes. rnIf automatic flushing is enabled at creation time, then the stream will be flushed each time a line is terminated or a newline character is written. rnrnMethods in this class never throw I/O exceptions. Client code may inquire as to whether any errors have occurred by invoking the checkError method. rnrnNote: This class is provided primarily for use in debugging, and for compatibility with existing code; new code should use the PrintWriter class. rnrnrn无论参数,方法都是一样的,究竟有什么不同?rnrnrn

没有更多推荐了,返回首页