异常:IOException:Stream Closed

异常提示
  Exception in thread “main” java.io.IOException: Stream Closed
  流被关闭了。
代码如下
  写的是一个把多个被切割的MP3文件合并成一个MP3文件。

public class MergeFileDemo{
	public static void main(String[] args) throws IOException {
		File dir=new File("gril");
		mergeFile(dir);
	}

	public static void mergeFile(File dir) throws IOException {
		//
		ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();
		for (int i = 1; i <= 5; i++) {
			al.add(new FileInputStream(new File(dir,i+".part")));
			Enumeration<FileInputStream> en=Collections.enumeration(al);
			SequenceInputStream sis=new SequenceInputStream(en);
			FileOutputStream fos=new FileOutputStream(new File(dir,"丐帮主题.mp3"));
			byte[] buf=new byte[1024];
			int  len=0;
			while((len=sis.read(buf))!=-1) {
				fos.write(buf,0,len);
			}
		fos.close();
		sis.close();
		}
	}
}

问题分析

  流被关闭肯定是fos.close();和sis.close();出了问题,仔细检查发现关闭流写在了for循环里面,第一次循环时就关掉了流。而且这个for循环时将所有文件添加al.add();后就结束了,这里将后面的代码也写进去了,所以造成了异常。

解决方法

	fos.close();
	sis.close();

  将流关闭写在for循环外面。将for循环代码块修改为下,也就是将}放到al.add();后面。

	for (int i = 1; i <= 5; i++) {
		al.add(new FileInputStream(new File(dir,i+".part")));
	}
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值