读书人

关于IO中FileInputStream流以上代码

发布时间: 2012-09-06 10:37:01 作者: rapoo

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

读书人网 >J2SE开发

热点推荐