public static final int READ_BUFFER_SIZE = 1024;
/**
* 读取流中的字符到数组
* @param in 该方法执行完成不会关闭流
* @param limit 读取大小限制
* @return
* @throws IOException
*/
public static byte[] readStreamAsByteArray(InputStream in, int limit) throws IOException {
if (in == null) {
return new byte[0];
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[READ_BUFFER_SIZE];
int len = -1;
int temp = limit - READ_BUFFER_SIZE;
while ((len = in.read(buffer)) != -1) {
output.write(buffer, 0, len);
if(output.size() > temp) {
if(output.size() == limit) {
break;
}
byte[] buffer2 = new byte[limit - output.size()];
while ((len = in.read(buffer2)) != -1) {
output.write(buffer2, 0, len);
if(output.size() == limit) {
break;
}
buffer2 = new byte[limit - output.size()];
}
break;
}
}
return output.toByteArray();
}
上面代码用于从InputStream中读取特定长度的数据,把文件分断处理时用到
