Chinaunix首页 | 论坛 | 博客
  • 博客访问: 240882
  • 博文数量: 55
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 261
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-19 01:34
文章分类

全部博文(55)

文章存档

2013年(37)

2009年(6)

2008年(12)

我的朋友

分类: Java

2013-09-05 20:08:17

原文地址:InputStreamReader 作者:chendong292

       字节流是由字节组成的,字符流是由字符组成的. Java里字符由两个字节组成.字节流是最基本的,所有的InputStream和OutputStream的子类都是,主要用在处理二进制数据,它是按字节来处理的但实际中很多的数据是文本,又提出了字符流的概念,它是按虚拟机的encode来处理,也就是要进行字符集的转化。在从字节流转化为字符流时,实际上就是byte[]转化为String时,public String(byte bytes[], String charsetName)有一个关键的参数字符集编码,通常我们都省略了,那系统就用操作系统默认的lang。

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

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

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

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

点击(此处)折叠或打开

  1. import java.io.*;
  2. public class InputStreamReaderDemo
  3. {
  4.  public static void main(String[] args)throws IOException
  5.  {
  6.   try
  7.   {
  8.    int b;
  9.    InputStreamReader isr = new InputStreamReader (new FileInputStream (new File ("D://testfile//input.log")));
  10.    System.out.println ("The content of text is:");
  11.    while ((b = isr.read()) != -1)//顺序读取文件text里的内容并赋值给整型变量b,直到文件结束为止。
  12.    {
  13.     System.out.print((char)b);
  14.    }
  15.    isr.close();
  16.   }
  17.   catch(FileNotFoundException e)
  18.   {
  19.    System.out.println(e);
  20.   }
  21.   catch(IOException e)
  22.   {
  23.    System.out.println(e);
  24.   }
  25.   catch(Exception e)
  26.   {
  27.    System.out.println(e);
  28.   }
  29.  }
  30. }

阅读(841) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~