InputStream类available和read方法可能读取不到完整的流数据

1、问题描述

项目需要一个将网络流InputStream转换为byte[]数组的方法,于是从网上找了下面的方法:

	private byte[] toByteArray(InputStream input) throws IOException {
	   		byte[] buffer = new byte[(int) in.available()];
		in.read(buffer);
		in.close();
                return buffer;
	}

该网络流是一张图像的数据,将流保存成本地图像展现时发现图像大小正确,内容仅上半部分正确、后半部分为黑白点阵。

2、分析

图像头部分正确(图像大小、格式等正确),图像内容缺失,应该是图像流没有读取完整导致的。

3、证实

翻看API文档:http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#available(),发现

available

public int available()
              throws IOException
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The 
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值