1

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

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 错误。

可能是什么问题?

4

1 回答 1

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();
于 2013-07-05T06:39:20.720 回答