Java关闭PDF错误

bon*_*sai 7 java pdf pdfbox

我有这个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");
}
Run Code Online (Sandbox Code Playgroud)

抛出这个:

11:45:07,017 WARN  [COSDocument] Warning: You did not close a PDF Document
Run Code Online (Sandbox Code Playgroud)

而且我不知道为什么要扔掉这个1,2,3或更多.

我发现COSDocument是一个类并且有close()方法,但是我没有使用这个类.

我有这个进口:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

Jon*_*eet 13

你正在加载PDDocument但没有关闭它.我怀疑你需要这样做:

String textOfPdf;
PDDocument doc = PDDocument.load("doc");
try {
    textOfPdf = pdfs.getText(doc);
} finally {
    doc.close();
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*n M 7

刚刚遇到这个问题.使用Java 7,您可以这样做:

try(PDDocument document = PDDocument.load(input)) {
  // do something  
} catch (IOException e) {
  e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

因为PDDocument implements Closeable,try块最后会自动调用它的close()方法.


dog*_*ane 5

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

这是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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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