//导入类import java.io.*;public class Test {
public  static void main(String args [] ){ 
        //声明输入流引用
FileInputStream fil = null;
//声明输出流引用
FileOutputStream fol = null;
        try{
            //生成代表输入流的对象
         fil = new FileInputStream("d:/javaworkspace/Test/src/from.txt");
         //生成代表输出流的对象
         fol = new FileOutputStream("d:/javaworkspace/Test/src/to.txt");
         //生成一个字节字节数组
         byte [] buffer = new byte[100];
         //调用该输入流对象的read方法,读取数据
         //(数组,偏移量,长度)
         fil.read(buffer,0,buffer.length);
         //确定输出长度
         int temp =fil.read(buffer,0,buffer.length);//为什么会提示数组越界?
         //调用该输出流对象的write方法,输出数据
         fol.write(buffer,0,temp);
         //将ascii码还原
         /*String s =new String(buffer);
            //调用一个String对象的trim方法,将会去除掉这个字符串的首尾的空格和空字符
            s = s.trim();
         System.out.println(s);*/
        }
        catch(Exception e){
         System.out.println(e);
        }

}}
int temp =fil.read(buffer,0,buffer.length);//这一个为什么会提示数组越界?

解决方案 »

  1.   

    public int read(byte[] b,
                    int off,
                    int len)
    抛出异常的原因有三个:如果 off 为负,len 为负,或者 len 大于 b.length - off,会抛出IndexOutOfBoundsEXception()
    如果 len 为 0,则不读取任何字节并返回 0;否则,尝试读取至少一个字节。如果因为流位于文件末尾而没有可用的字节,则返回值 -1;form.txt文件中不到100个字节,len返回值为-1,所有抛出数组越界异常。
      

  2.   

    出现错误的应该是fol.write(buffer,0,temp)这里,from.txt中没有100个字节是,temp=-1;