首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

关于IO中FileInputStream流,以上代码抛错误

2012-09-06 
关于IO中FileInputStream流,以下代码抛异常。[codeJava][/code]package com.io.testimport java.io.FileI

关于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();    }} 

热点排行