Search code examples
javapdfout-of-memoryarraysfileinputstream

java.lang.OutOfMemoryError when trying to read huge PDF file to byte array


I'm trying to read huge pdf file using byte Array, Here is my code for it.

String RESULT "D/new/certficateVisualFinal.pdf";
    try {
        FileInputStream fileInputStream=null;

        File file = new File(RESULT);

        byte[] bFile = new byte[(int) file.length()];


            //convert file into array of bytes
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(bFile);
        fileInputStream.close();

        reader = new PdfReader(bFile);
        pdfStamper = new PdfStamper(reader, new FileOutputStream(outPut));

        pdfStamper.setOutlines(outlineVisual);
        pdfStamper.setFormFlattening(true);

 } catch (IOException e) {
    e.printStackTrace();
 } catch (Exception e) {
    e.printStackTrace();
 }

But I got a OutOfMemoryErro when trying to

fileInputStream.read(bFile);

This is the Error

Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:220)

please help me.Thank you.


Solution

  • Don't use the byte array at all. PdfReader has a constructor with an InputStream parameter, so you can just pass your FileInputStream directly to that.