1

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 ?

1 Answer 1

6

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();
Sign up to request clarification or add additional context in comments.

5 Comments

yes i will definitely accept, i had an issue before there were some files which was not opening so i had used ByteArrayOutputStream , so i am checking for that,
William thanks a lot, it works perfectly fine, but there a delay in loading the file for first time , how can we avoid that any idea?
Not sure, id have to see more of the code. If its executing slowly at first it could be because many classes are being loaded, or the compiler could be optimizing at runtime.
fileInputStream is always return null
My guess is that's because you're not pointing correctly to your resource.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.