InputStreamReader 的使用,实现字节的输入流到字符的输入流的操作
package com.atguigu.java;
import org.junit.Test;
import java.io.*;
/**
* 处理流之二:转换流的使用
* 1. 转换流:属于字符流(看结尾)
* InputStreamReader: 将一个字节的输入流转换为字符的输入流
* OutputStreamWriter:将一个字符的输出流转换为字节的输出流
* 2. 作用: 提供字节流和字符流之间的转换
* 3. 字节数组 --- > 字符数组字符串 解码
* 字符数组字符串--- >字节数组 编码
* 4. 字符集
*
* @author liangqichen
* @create 2021-10-16 11:35
*/
public class InputStreamReaderTest {
/*
此时处理异常的话,仍然应该使用try catch finally
InputStreamReader 的使用,实现字节的输入流到字符的输入流的操作
*/
@Test
public void test1() throws IOException {
FileInputStream fis = new FileInputStream("dbcp.txt");
InputStreamReader isr = new InputStreamReader(fis); // 使用系默认的字符集
// 参数2 指明了字符集,具体使用哪个字符集。取决于dbcp.txt保存时使用的字符集
// InputStreamReader isr =new InputStreamReader(fis,"UTF-8"); // 使用系默认的字符集
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1){
String str = new String(cbuf, 0, len);
System.out.print(str);
}
isr.close();
}
}