我有一个拥有200MB数据的FileInputStream.我必须从输入流中检索字节.
我正在使用下面的代码将InputStream转换为字节数组.
private byte[] convertStreamToByteArray(InputStream inputStream) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
int i;
while ((i = inputStream.read()) > 0) {
bos.write(i);
}
} catch (IOException e) {
e.printStackTrace();
}
return bos.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)
在将如此大的数据转换为字节数组时,我得到了OutOfMemory异常.
请告诉我将InputStream转换为字节数组的任何可能的解决方案.
小智 9
为什么要将200MB文件保存在内存中?你打算用字节数组做什么?
如果要将其写入OutputStream,首先准备好OutputStream,然后一次读取一个块的InputStream,然后将块写入OutputStream.你永远不会在内存中存储超过块.
例如:
public static void pipe(InputStream is, OutputStream os) throws IOException {
int read = -1;
byte[] buf = new byte[1024];
try {
while( (read = is.read(buf)) != -1) {
os.write(buf, 0, read);
}
}
finally {
is.close();
os.close();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码将采用两个流并将一个管道连接到另一个.
| 归档时间: |
|
| 查看次数: |
7561 次 |
| 最近记录: |