字符流类库详解

对着源码,理一理java.io中基于字符的I/O:ReaderWriter

字符读取Reader

java.io.Reader (implements java.io.Closeable, java.lang.Readable) 读取字符的抽象类

//子类需要实现read,读取字符到一个字符数组中
abstract public int read(char cbuf[], int off, int len) throws IOException

类图:


字符流类库详解_第1张图片
字符流读取类图
  • java.io.BufferedReader 缓冲流,默认缓冲区大小8M,使用时,通常配合一个其他效率比较低的Reader,比如FileReaderInputStreamReader。如果使用FileReader,每读取一个字符,或者一行,需要访问一次磁盘,然后转换成字符再返回,效率很低。使用缓冲流可以明显减少访问磁盘的次数,从而提高读取效率。
    • java.io.LineNumberReader BufferedReader的子类,支持记录lineNumber
  • java.io.CharArrayReader 内部包含一个字符数组缓冲,可以作为一个字符输入流使用
/** The character buffer. */
    protected char buf[];
  • java.io.FilterReader 代理构造时传入的一个其他的Reader
    /**
     * The underlying character-input stream.
     */
    protected Reader in;
  • java.io.PushbackReader FilterReader的子类,顾名思义,支持重读
  • java.io.InputStreamReader 构造是传入的是一个InputStream,表示还是基于字节流的,每次读取一个字符,需要从底层字节流中根据需要读取多个字节。为了提高效率,通常把InputStreamReader包在一个BufferedReader 中使用。
    • java.io.FileReader InputStreamReader的子类。从文件中读取字符。如果需要从文件中读取基本类型,还是要使用FileInputStream
  • java.io.PipedReader Piped character-input streams.
  • java.io.StringReader A character stream whose source is a string.
字符写入Writer

java.io.Writer (implements java.lang.Appendable, java.io.Closeable, java.io.Flushable)

//所有子类必须实现对字符数组的写入
abstract public void write(char cbuf[], int off, int len) throws IOException;

类图:


字符流类库详解_第2张图片
字符流写入类图
  • java.io.BufferedWriter 先将缓冲区写满,再向底层Writer一把写入。提高效率。
 * 

In general, a Writer sends its output immediately to the underlying * character or byte stream. Unless prompt output is required, it is advisable * to wrap a BufferedWriter around any Writer whose write() operations may be * costly, such as FileWriters and OutputStreamWriters. For example, * *

 * PrintWriter out
 *   = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
 * 
* * will buffer the PrintWriter's output to the file. Without buffering, each * invocation of a print() method would cause characters to be converted into * bytes that would then be written immediately to the file, which can be very * inefficient.
  • java.io.CharArrayWriter 将字符写入一个字符数组char buf[]中。
  • java.io.FilterWriter
  • java.io.OutputStreamWriter
//构造时仍然需要OutputStream
public OutputStreamWriter(OutputStream out)
  • java.io.FileWriter OutputStreamWriter的子类,层层包裹后,最终还是要落到通过字节输出流写入。只是为了简化使用。
    public FileWriter(File file) throws IOException {
        super(new FileOutputStream(file));
    }
    public FileWriter(String fileName) throws IOException {
        super(new FileOutputStream(fileName));
    }
  • java.io.PipedWriter
  • java.io.PrintWriter 按格式要求打印到底层字符输出流中。
    /**
     * The underlying character-output stream of this
     * PrintWriter.
     * @since 1.2
     */
    protected Writer out;
  • java.io.StringWriter 写到一个字符缓冲区,然后可以被用来生成一个字符串。内部使用StringBuffer

引用
Hierarchy For Package java.io

你可能感兴趣的:(字符流类库详解)