Java 中 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;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。