InputStreamReader和OutputStreamWriter 是字节流通向字符流的桥梁:它使用指定的 charset 读写字节并将其解码为字符。
InputStreamReader 的作用是将“字节输入流”转换成“字符输入流”。它继承于Reader。
OutputStreamWriter 的作用是将“字节输出流”转换成“字符输出流”。它继承于Writer。

转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_21.html

更多内容请参考:java io系列01之 "目录"

InputStreamReader和OutputStreamWriter源码分析

1. InputStreamReader 源码(基于jdk1.7.40)

 1 package java.io;
 2 
 3 import java.nio.charset.Charset;
 4 import java.nio.charset.CharsetDecoder;
 5 import sun.nio.cs.StreamDecoder;
 6 
 7 
 8 // 将“字节输入流”转换成“字符输入流”
 9 public class InputStreamReader extends Reader {
10 
11     private final StreamDecoder sd;
12 
13     // 根据in创建InputStreamReader,使用默认的编码
14     public InputStreamReader(InputStream in) {
15         super(in);
16         try {
17             sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object
18         } catch (UnsupportedEncodingException e) {
19             // The default encoding should always be available
20             throw new Error(e);
21         }
22     }
23 
24     // 根据in创建InputStreamReader,使用编码charsetName(编码名)
25     public InputStreamReader(InputStream in, String charsetName)
26         throws UnsupportedEncodingException
27     {
28         super(in);
29         if (charsetName == null)
30             throw new NullPointerException("charsetName");
31         sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
32     }
33 
34     // 根据in创建InputStreamReader,使用编码cs
35     public InputStreamReader(InputStream in, Charset cs) {
36         super(in);
37         if (cs == null)
38             throw new NullPointerException("charset");
39         sd = StreamDecoder.forInputStreamReader(in, this, cs);
40     }
41 
42     // 根据in创建InputStreamReader,使用解码器dec
43     public InputStreamReader(InputStream in, CharsetDecoder dec) {
44         super(in);
45         if (dec == null)
46             throw new NullPointerException("charset decoder");
47         sd = StreamDecoder.forInputStreamReader(in, this, dec);
48     }
49 
50     // 获取解码器
51     public String getEncoding() {
52         return sd.getEncoding();
53     }
54 
55     // 读取并返回一个字符
56     public int read() throws IOException {
57         return sd.read();
58     }
59 
60     // 将InputStreamReader中的数据写入cbuf中,从cbuf的offset位置开始写入,写入长度是length
61     public int read(char cbuf[], int offset, int length) throws IOException {
62         return sd.read(cbuf, offset, length);
63     }
64 
65     // 能否从InputStreamReader中读取数据
66     public boolean ready() throws IOException {
67         return sd.ready();
68     }
69 
70     // 关闭InputStreamReader
71     public void close() throws IOException {
72         sd.close();
73     }
74 }
View Code

相关文章:

  • 2021-08-18
  • 2021-05-29
  • 2022-12-23
  • 2021-05-22
  • 2021-12-03
  • 2021-10-02
  • 2022-12-23
猜你喜欢
  • 2021-10-25
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2021-11-20
相关资源
相似解决方案