文章目录
一、 转换流概述
- 转换流提供了在字节流和字符流之间的转换
- Java API提供了两个转换流:
InputStreamReader
:将InputStream转换为Reader
OutputStreamWiter
:将Writer转换为OutputStream- 字节流中的数据都是字符时,转成字符流操作更高效
很多时候转换流用来处理文件乱码问题。实现编码和解码的功能
二、转换流的使用
转换流机制
2.1 InputStreamReader
testForInputStreamReader:
@Test
public void testForInputStreamReader(){
FileInputStream fis = null;
InputStreamReader irs1 = null;//根据文件保存的编码格式确定应该使用的字符集
try {
fis = new FileInputStream("hello.txt");
// InputStreamReader irs = new InputStreamReader(fis);//使用系统默认的字符集
// irs1 = new InputStreamReader(fis,"GBK");//输出乱码:鍚炬湁姊︼紒鍚惧繀涓轰箣琛岋紒
irs1 = new InputStreamReader(fis,"UTF-8");//输出:吾有梦!吾必为之行!
char[] cbfu = new char[20];
int len;
while ((len =