日期:2014-05-20  浏览次数:20759 次

关于IO中FileInputStream流,以下代码抛异常。
[code=Java][/code]
package com.io.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class BytesStreamTest
{

  private static int BUFFER_SIZE = 1024;

  public static void main(String[] args) throws Exception
  {
  readTest();  
  }
   
  //此方法抛异常——如何解决?
  public static void readTest() throws Exception
  {
  FileInputStream fis = new FileInputStream("output.txt");

  byte[] buf = new byte[BUFFER_SIZE];
  int ch = 0;
  while((ch = fis.read()) != 0)
  {
  System.out.println(new String(buf,0,ch));
  }

  fis.close();
  }


}


------解决方案--------------------
Java code
public static void readTest() throws Exception {
        FileInputStream fis = new FileInputStream("output.txt");

        byte[] buf = new byte[1024];
        int ch = 0;
        if( 0 != (ch = fis.read(buf))){
            System.out.println(new String(buf, 0, ch));
        }

        fis.close();
    }

------解决方案--------------------
你程序当中对buf的使用有问题,buf只是一个 比1byte更大的缓存,正确的方法给你贴出来
Java code


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BytesStreamTest
{

    private static int BUFFER_SIZE = 1024;

    public static void main(String[] args) throws Exception
    {
        readTest();
    }


    public static void readTest() throws Exception
    {
        FileInputStream fis = new FileInputStream("output.txt");
        
        byte[] buf = new byte[BUFFER_SIZE];
        int ch = 0;
        while((ch = fis.read(buf)) != -1)
        {
            
            System.out.println(new String(buf,0,ch));
        }

        fis.close();
    }


}