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