1. InputStreamReader的使用
InputStreamReader(InputStream is):用默认的编码读取数据
InputStreamReader(InputStream is,String charsetName):用指定的编码读取数据
2. 代码示例:
(1) InputStreamReader读方法下面两种经常用到两种方法:(继承自父类Reader)
1 public int read()
1 public int read(char[] cbuf)
(2)
1 package cn.itcast_02; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 7 /* 8 * InputStreamReader(InputStream is):用默认的编码读取数据 9 * InputStreamReader(InputStream is,String charsetName):用指定的编码读取数据 10 */ 11 public class InputStreamReaderDemo { 12 public static void main(String[] args) throws IOException { 13 // 创建对象 14 // InputStreamReader isr = new InputStreamReader(new FileInputStream( 15 // "osw.txt")); 16 17 // InputStreamReader isr = new InputStreamReader(new FileInputStream( 18 // "osw.txt"), "GBK"); 19 20 InputStreamReader isr = new InputStreamReader(new FileInputStream( 21 "osw.txt"), "UTF-8"); 22 23 // 读取数据 24 // 一次读取一个字符 25 int ch = 0; 26 while ((ch = isr.read()) != -1) { 27 System.out.print((char) ch); 28 } 29 30 // 释放资源 31 isr.close(); 32 } 33 }
运行结果: