
第一种,写法最简单的。使用原生IO,一个字节一个字节读:
//一个字符一个字符读,太慢
int i;
while((i=in.read()) != -1){
i = in.read();
arr[j++] = i;
}
这种方式非常的慢,极为不推荐。
第二种,一次读完:
byte[] arr = new byte[in.available()];
in.read(arr);
这种和第一种相反,一次读完流,这种情况在文件稍大时会非常占用内存,也极为不推荐。
第三种,缓冲读:
byte[]buff = new byte[1024];
int eachlength = 0;
int total = 0;
while((eachlength = in.read(buff)) != -1){
System.arraycopy(buff, 0, arr, total, eachlength);
total += eachlength;
}
这种方式每次读取1024字节,然后copy给arr目标数组中。
第四种,借助commons-io:
org.apache.commons.io.IOUtils.toByteArray(input)
它源码中的实现是:
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;
}