在commons-io包中org.apache.commons.io.IOUtils类的toByteArray(InputStream input)已经有实现了,我们可以参考下思路,完成我们的方法,我们可以用类似下面的代码实现inputStream转化为byte[]数组public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
下面是IOUtils中摘录出与toByteArray相关的方法
org.apache.commons.io.IOUtils.toByteArray
方法如下:
public static byte[] toByteArray(InputStream input)
throws IOException
{
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
public static int copy(InputStream input, OutputStream output)
throws IOException
{
long count = copyLarge(input, output);
if (count > 2147483647L) {
return -1;
}
return (int)count;
}
public static long copyLarge(InputStream input, OutputStream output)
throws IOException
{
byte[] buffer = new byte[4096];
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
文章详细出处:http://blog.csdn.net/zdwzzu2006/article/details/7745827