刚好在看深入Java web技术内幕这本书,书里提到了Java IO,之前日常的工作中一直对各种IO类之间的关系理不清楚,正好趁此机会走读下源码做下总结
IO类
人类识别字符,机器识别字节,如果需要对字符进行机器间的传输,需要将字符向字节进行转化,Java针对2种数据格式,有不同的IO类:
- 基于字节操作的IO接口:InputStream和OutputStream
由于OutputStream和InputStream的相对关系,我们只讲InputStream
InputStream 是所有字节输入类的基类,它的作用就是从输入源读取字节到内存
类层次结构如下:
- 基于字符操作的IO接口:Writer和Reader
Reader 是所有字符输入类的基类,它的作用就是从输入源读取字符到内存
类层次结构如下:
InputStream/Reader/InputStreamReader3者之间的关系:
1.InputStreamReader是字节流和字符流之间的桥梁,InputStreamReader继承了Reader类,InputStreamReader的注释如下:
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified {@link java.nio.charset.Charset charset}. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
2.更直白的理解:InputStreamReader将InputStream中读取的字节转换为字符,下面的代码将3者关系表现了出来:
// 创建字节输入流
FileInputStream fi = new FileInputStream("/Users/ali/10_python/get-pip.py");
// 字节输入流向字符输入流转换
InputStreamReader ir = new InputStreamReader(fi, "UTF-8");
// 从InputStreamReader中读取到BufferedReader,实现高效的字符行读取
BufferedReader br = new BufferedReader(ir);
StringBuilder contentBuffer = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
contentBuffer.append(line);
System.out.println(line);
}
网友评论