InputStreamReader(继承Reader)
简介: 将字节流转换为字符流, 字节流通向字符流的桥梁,如果不指定字符集编码,则解码过程
将使用平台默认的字符编码,如:UTF-8
文本文件存储是A编码,然后如果以B编码进⾏读取则会乱码
//使用系统默认编码集
public InputStreamReader(InputStream in)
//指定指定编码集创建对象
public InputStreamReader(InputStream in, String charsetName)
常用API
int read()
讲解:读取单个字符
int read(char[] cbuf, int off, int len)
讲解:读取一部分字符到数组里面,从数组下标off处放置length长度的字符
int read(char []cbuf)
讲解:将读取到的字符存到数组中,返回读取的字符数
void close()
讲解:关闭流释放资源
代码:
public static void main(String[] args)throws Exception{
test1("C:\\Users\\Administrator\\Desktop\\test\\9.txt");
}
public static void test1(String path)throws Exception{
InputStream in=new FileInputStream(path);
InputStreamReader ins=new InputStreamReader(in,"GBK");
BufferedReader reader=new BufferedReader(ins);
//数组输出
// char[] chars=new char[1024];
// int size;
// while ((size=reader.read(chars,0,chars.length))!=-1){
// System.out.println(new String(chars,0,size));
// }
//行输出
String line;
while ((line=reader.readLine())!=null){
System.out.println(line);
}
reader.close();
}
效果截图: