Goofy
Goofy

Reputation: 6128

OutOfMemory Error in ByteArrayOutputStream while writing 'n' number of files

i am writing the PDF's to sdcard and using the below code :

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();

It works fine if i am trying to write 20 PDFs in one shot, but if its more than that it gives me OutOfMemory error.

what might be the issue ?

Upvotes: 1

Views: 3572

Answers (1)

William Morrison
William Morrison

Reputation: 11006

You are storing the entire file into RAM with your ByteArrayOutputStream, then copying it from RAM onto disk. This is likely what's causing your OutOfMemoryError.

It would be much more efficient to read a chunk into RAM, and then flush to disk immediately repeatedly. I've rewritten your code to do this.

    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();

Upvotes: 6

Related Questions