写入'n'个文件时,ByteArrayOutputStream中出现OutOfMemory错误

时间:2013-07-05 06:21:32

标签: android out-of-memory

我正在将PDF写入SD卡并使用以下代码:

byte[] data = new byte[20000];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
InputStream fileInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);

while ((nRead = fileInputStream.read(data, 0, data.length)) != -1) {
    buffer.write(data, 0, nRead);
}

buffer.flush();
byte[] bytesToWrite = buffer.toByteArray();
fileInputStream.read(bytesToWrite);
fileInputStream.close();

FileOutputStream fileOutputStream = null;
String outputFileName = outputDirName + "/" + fileName;
fileOutputStream = new FileOutputStream(outputFileName);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bos.write(bytesToWrite);
bos.flush();
bos.close();

如果我试图在一次拍摄中写入20个PDF,它可以正常工作,但如果它超过它,它会给我OutOfMemory错误。

可能是什么问题?

1 个答案:

答案 0 :(得分:6)

您使用ByteArrayOutputStream将整个文件存储到RAM中,然后将其从RAM复制到磁盘上。这可能是导致OutOfMemoryError的原因。

将块读入RAM,然后立即重复刷新到磁盘会更高效。我已经重写了你的代码来执行此操作。

    byte[] data = new byte[20000];
    FileOutputStream fileOutputStream = null;
    String outputFileName = outputDirName + "/" + fileName;
    fileOutputStream = new FileOutputStream(outputFileName);

    int nRead;
    InputStream fileInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    while ((nRead = fileInputStream.read(data, 0, data.length)) != -1) {
        fileOutputStream.write(data,0,nRead);
    }
    fileInputStream.close();
    fileOutputStream.flush();
    fileOutputStream.close();