Java close PDF error

丶灬走出姿态 提交于 2019-12-05 22:35:32

问题


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 :)


回答1:


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



回答2:


Just had this issue, too. With Java 7 you can do this:

try(PDDocument document = PDDocument.load(input)) {
  // do something  
} catch (IOException e) {
  e.printStackTrace();
}

Because PDDocument implements Closeable, the try block will automagically call its close() method at the end.




回答3:


This warning is emitted when the pdf document is finalised and hasn't been closed.

Here is the finalize method from COSDocument:

/**
 * Warn the user in the finalizer if he didn't close the PDF document. The method also
 * closes the document just in case, to avoid abandoned temporary files. It's still a good
 * idea for the user to close the PDF document at the earliest possible to conserve resources.
 * @throws IOException if an error occurs while closing the temporary files
 */
protected void finalize() throws IOException
{
    if (!closed) {
        if (warnMissingClose) {
            log.warn( "Warning: You did not close a PDF Document" );
        }
        close();
    }
}

To get rid of this warning, you should explicitly call close on the document when you are done with it.



来源:https://stackoverflow.com/questions/4968491/java-close-pdf-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!