ByteArrayOutputStream 大文件内存溢出
曹某 2017-12-11 05:26:55 在用到ByteArrayOutputStream 将文件转为字节的时候 就遇到内存溢出的问题 400MB左右的文件能行。但是800多MB的文件就会出错。求大神指点指点...
代码如下:
public static byte[] getBytes(String filePath) {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return buffer;
}
标记的一行是主要报错的地方。这个地方主要是一次性将东西读到内存中导致的内存溢出 但是不知道该如何解决