关于IO中FileInputStream流,以下代码抛异常。

Hongh12580 2012-07-31 10:33:23

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


}
...全文
245 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Hongh12580 2012-08-01
  • 打赏
  • 举报
回复
受教了,下次注意。
pingchangxinli 2012-07-31
  • 打赏
  • 举报
回复
LZ,首先要把自己遇到的错误贴出来,不同的错误有不同的解决办法,你只是说抛出错误,谁知道是什么错误,靠猜??
Hongh12580 2012-07-31
  • 打赏
  • 举报
回复
谢谢了,大意了。
风尘中国 2012-07-31
  • 打赏
  • 举报
回复
你程序当中对buf的使用有问题,buf只是一个 比1byte更大的缓存,正确的方法给你贴出来


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


}


brightyq 2012-07-31
  • 打赏
  • 举报
回复
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();
}

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧