java Java关闭PDF错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4968491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:50:58  来源:igfitidea点击:

Java close PDF error

javapdfpdfbox

提问by bonsai

I have this java code:

我有这个java代码:

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.

我不知道为什么,但要扔 1、2、3 或更多。

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

我发现 COSDocument 是一个类并且有 close() 方法,但我没有在任何地方使用这个类。

I have this imports:

我有这个进口:

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

Thanks :)

谢谢 :)

回答by Jon Skeet

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

您正在加载PDDocument但未关闭它。我怀疑你需要做:

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

回答by Benjamin M

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

刚好也有这个问题。使用 Java 7,您可以这样做:

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

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

因为PDDocument implements Closeabletry块会close()在最后自动调用它的方法。

回答by dogbane

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

当 pdf 文档完成且尚未关闭时,会发出此警告。

Here is the finalizemethod from COSDocument:

这是finalize来自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 closeon the document when you are done with it.

要消除此警告,您应该close在完成后明确调用该文档。