import java.io.*;
public class InputStreamTest
{
public static void main(String[] args)
{
//先创建一个输入流;
FileInputStream fis = null;
//记录字节长度;
int hasRead = 0;
//声明一个字节数组来存字节。
byte buff[] = new byte[1024];//换成3读就会出现乱码
try
{
//为流类赋值;
fis = new FileInputStream("InputStreamTest.java");
//开始循环读取内容了;
while((hasRead = fis.read(buff)) > 0)
{
System.out.print(new String(buff));
}
}

catch(IOException e)
{
e.printStackTrace();

finally(finally应该放哪呢,放这里老报错)
{
if(fis != null)
fis.close();//close()本身就抛出异常;
}

}
}
问题:流是怎么实现读取的。如果我把1024改成3那么到中文时就会出现乱码,字节读取时是读满三个然后转换一次,遇到中文是不是要读2次才合成一个中文,
还有如果我把它换成字符流,一个不是就能读2个英文,可是为什么不是呢,求解,书上说有什么指针。

解决方案 »

  1.   

    中文字符是两个字节的。你改成3当然会报错。
    你代码还少了个括号,异常没有处理。package com.walkman.exercise.one;import java.io.*;public class InputStreamTest {
    public static void main(String[] args) {
    // 先创建一个输入流;
    FileInputStream fis = null;
    // 记录字节长度;
    int hasRead = 0;
    // 声明一个字节数组来存字节。
    byte buff[] = new byte[1024];// 换成3读就会出现乱码
    try {
    // 为流类赋值;
    fis = new FileInputStream("InputStreamTest.java");
    // 开始循环读取内容了;
    while ((hasRead = fis.read(buff)) > 0) {
    System.out.print(new String(buff));
    }
    } catch (IOException e) {
    e.printStackTrace();
    } finally {// (finally应该放哪呢,放这里老报错)
    if (fis != null)
    try {
    fis.close();
    } catch (IOException e) { e.printStackTrace();
    }
    }
    }
    }
    修改后的代码如上。
      

  2.   

    中文字符、英文字符都是“一个字符”,只不过占用空间不一样,你设置好编码格式,java能分辨出来,这样中英文字符就能“混合着”读出来了。。仅供参考哈
      

  3.   

    想问下如果我把它换成字符流while ((hasRead = fis.read(buff)) > 0) {
                    System.out.print(new String(buff,0,hasRead));
                }
    后,为什么会老报:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
    ex out of range: -1
            at java.lang.String.<init>(String.java:208)
            at ReaderTest.main(ReaderTest.java:18)
      

  4.   

    import java.io.*;
    public class ReaderTest
    {
    public static void main(String[] args)
    {
    //声明一个字符流;
    FileReader fid = null;
    //声明一个字符数组,来存字符;
    char[] buff = new char[24];
    //来记录返回的字节个数
    int hasRead = 0;
    try
    {
    fid = new FileReader("ReaderTest.java");
    //循环读取内容
    while((hasRead = fid.read(buff)) > 0);
    {
    System.out.print(new String(buff,0,hasRead));
    }
    }
    catch(IOException e)
    {
    e.printStackTrace();
    }
    /*finally
    {
    if(fid != null)
    {
    fid.close();
    }
    }*/
    }
    }这个就会报什么下标溢出的意思吧,要把while((hasRead = fid.read(buff)) > 0);
    {
    System.out.print(new String(buff,0,hasRead));
    (buff,0,hasRead)改成(buff);就会输出
    ();
                            }
                    }*/
            }
    }e
    求解求解