Java close PDF error

bonsai picture bonsai · Feb 11, 2011 · Viewed 14k times · Source

I have this java code:

try {
    PDFTextStripper pdfs = new PDFTextStripper();

    String textOfPDF = pdfs.getText(PDDocument.load("doc"));

    doc.add(new Field(campo.getDestino(),
            textOfPDF,
            Field.Store.NO,
            Field.Index.ANALYZED));

} catch (Exception exep) {
    System.out.println(exep);
    System.out.println("PDF fail");
}

And throws this:

11:45:07,017 WARN  [COSDocument] Warning: You did not close a PDF Document

And I don't know why but throw this 1, 2, 3, or more.

I find that COSDocument is a class and have close() method, but I don't use this class nowhere.

I have this imports:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

Thanks :)

Answer

Jon Skeet picture Jon Skeet · Feb 11, 2011

You're loading a PDDocument but not closing it. I suspect you need to do:

String textOfPdf;
PDDocument doc = PDDocument.load("doc");
try {
    textOfPdf = pdfs.getText(doc);
} finally {
    doc.close();
}