InputStreamReader:是字节流通向字符流的桥梁
1 package com.itheima.demo03.ReverseStream; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 7 /* 8 java.io.InputStreamReader extends Reader 9 InputStreamReader:是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。(解码:把看不懂的变成能看懂的) 10 11 继承自父类的共性成员方法: 12 int read() 读取单个字符并返回。 13 int read(char[] cbuf)一次读取多个字符,将字符读入数组。 14 void close() 关闭该流并释放与之关联的所有资源。 15 构造方法: 16 InputStreamReader(InputStream in) 创建一个使用默认字符集的 InputStreamReader。 17 InputStreamReader(InputStream in, String charsetName) 创建使用指定字符集的 InputStreamReader。 18 参数: 19 InputStream in:字节输入流,用来读取文件中保存的字节 20 String charsetName:指定的编码表名称,不区分大小写,可以是utf-8/UTF-8,gbk/GBK,...不指定默认使用UTF-8 21 使用步骤: 22 1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称 23 2.使用InputStreamReader对象中的方法read读取文件 24 3.释放资源 25 注意事项: 26 构造方法中指定的编码表名称要和文件的编码相同,否则会发生乱码 27 */ 28 public class Demo03InputStreamReader { 29 public static void main(String[] args) throws IOException { 30 //read_utf_8(); 31 read_gbk(); 32 } 33 34 35 /* 36 使用InputStreamReader读取GBK格式的文件 37 */ 38 private static void read_gbk() throws IOException { 39 //1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称 40 //InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\gbk.txt"),"UTF-8");//??? 41 InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\gbk.txt"),"GBK");//你好 42 43 //2.使用InputStreamReader对象中的方法read读取文件 44 int len = 0; 45 while((len = isr.read())!=-1){ 46 System.out.println((char)len); 47 } 48 //3.释放资源 49 isr.close(); 50 } 51 52 /* 53 使用InputStreamReader读取UTF-8格式的文件 54 */ 55 private static void read_utf_8() throws IOException { 56 //1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称 57 //InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\utf_8.txt"),"UTF-8"); 58 InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\utf_8.txt"));//不指定默认使用UTF-8 59 //2.使用InputStreamReader对象中的方法read读取文件 60 int len = 0; 61 while((len = isr.read())!=-1){ 62 System.out.println((char)len); 63 } 64 //3.释放资源 65 isr.close(); 66 } 67 }
个人官网yhqtv.com

浙公网安备 33010602011771号