一个读取文件的方法:
Android:
  public String  readFile(String fileName) throws Exception{
  ByteArrayOutputStream  outStream=new ByteArrayOutputStream();
  FileInputStream fis=context.openFileInput(fileName);
  byte [] buffer=new byte[1024];
          int length=fis.read(buffer);//1
 while(length != -1){//2
 outStream.write(buffer,0,lengt)
   }
  byte[] b= outStream.toByteArray();
  String s=new String(b);
 return s; 
  }
如上所示了:注释1和2处
这样写为什么会出现java.lang.OutOfMemoryError
是内存溢出吧!
我修改1,2处:如下:3,4
    public String  readFile(String fileName) throws Exception{
  ByteArrayOutputStream  outStream=new ByteArrayOutputStream();
  FileInputStream fis=context.openFileInput(fileName);
  byte [] buffer=new byte[1024];
          int length=0;//3
 while((length = fis.read(buffer)) != -1){//4
 outStream.write(buffer,0,lengt)
   }
  byte[] b= outStream.toByteArray();
  String s=new String(b);
 return s; 
  }
这样就没有问题了。真心求解释!   

解决方案 »

  1.   

     int length=fis.read(buffer);//1这在一直读
      

  2.   

     while((fis.read(buffer)) != -1){//4
     outStream.write(buffer,0,lengt)
       }
    试试
      

  3.   

    length = fis.read(buffer)) != -1){//4
    4这里不是也一直在读吗?4和1的差别在哪里呢?谢谢!
      

  4.   

    1是只读了一次,一直write就可能内存溢出
      

  5.   

    改成这样:
    byte [] buffer=new byte[1024];
              int length=0;//1
     while((length=fis.read(buffer)) != -1){//2
     outStream.write(buffer,0,lengt)
       }楼主写的代码中,1处虽然执行了一次,但依据楼主的情况该length恒不等于-1,导致2处无限循环,导致不停write,然后溢出。
      

  6.   

          int length=fis.read(buffer);//1
     while(length != -1){//2
     outStream.write(buffer,0,lengt)
       }这样理解:读了一次,length>-1,
    while无限执行!不断写io
      

  7.   

    差不多,不过未必是全部读取,是至多1024个字节,读一次只是从文件输入流中读取了至多1024个字节并存入byte数组中写入会溢出是因为写入动作在while的控制下重复将同一个byte数组数据写入输出流看下解释:
    public void write(byte[] b,
                      int off,
                      int len)
               throws IOException
    Writes len bytes from the specified byte array starting at offset off to this output stream.