字节流通向字符流的桥梁:InputStreamReader

public class InputStreamReader
   
   
    
    extends 
    
    Reader
   
   

InputStreamReader 是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。

每次调用 InputStreamReader 中的一个 read() 方法都会导致从底层输入流读取一个或多个字节。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节,使其超过满足当前读取操作所需的字节。

为了达到最高效率,可要考虑在 BufferedReader 内包装 InputStreamReader。例如:

 BufferedReader in
   = new BufferedReader(new InputStreamReader(System.in));


构造方法摘要
InputStreamReader(InputStream in)
          创建一个使用默认字符集的 InputStreamReader。
InputStreamReader(InputStream in, Charset cs)
          创建使用给定字符集的 InputStreamReader。
InputStreamReader(InputStream in, CharsetDecoder dec)
          创建使用给定字符集解码器的 InputStreamReader。
InputStreamReader(InputStream in, String charsetName)
          创建使用指定字符集的 InputStreamReader。
 
方法摘要
 voidclose()
          关闭该流并释放与之关联的所有资源。
 StringgetEncoding()
          返回此流使用的字符编码的名称。
 intread()
          读取单个字符。
 intread(char[] cbuf, int offset, int length)
          将字符读入数组中的某一部分。
 booleanready()
          判断此流是否已经准备好用于读取。

例:Demo

import java.io.*;
class InputStreamReaderDemo {
  public static void transReadNoBuf() throws IOException {
    /**
     * 没有缓冲区,只能使用read()方法。
     */
    //读取字节流
    //InputStream in = System.in;//读取键盘的输入。
    InputStream in = new FileInputStream("D:\\demo.txt");//读取文件的数据。
    //将字节流向字符流的转换。要启用从字节到字符的有效转换,
    //可以提前从底层流读取更多的字节.
    InputStreamReader isr = new InputStreamReader(in);//读取
    //综合到一句。
    //InputStreamReader isr = new InputStreamReader(
    //new FileInputStream("D:\\demo.txt"));
      
    char []cha = new char[1024];
    int len = isr.read(cha);
    System.out.println(new String(cha,0,len));
    isr.close();

  }
  public static void transReadByBuf() throws IOException {
    /**
     * 使用缓冲区 可以使用缓冲区对象的 read() 和  readLine()方法。
     */
    //读取字节流
    //InputStream in = System.in;//读取键盘上的数据
    InputStream in = new FileInputStream("D:\\demo.txt");//读取文件上的数据。
    //将字节流向字符流的转换。
    InputStreamReader isr = new InputStreamReader(in);//读取
    //创建字符流缓冲区
    BufferedReader bufr = new BufferedReader(isr);//缓冲
    //BufferedReader bufr = new BufferedReader(
    //new InputStreamReader(new FileInputStream("D:\\demo.txt")));可以综合到一句。
      /*int ch =0;
    ch = bufr.read();
    System.out.println((char)ch);
    */
    String line;
    while((line = bufr.readLine())!=null){
      System.out.println(line);
    }
    isr.close();
  }
}


  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值