【问题标题】:Java close PDF errorJava关闭PDF错误
【发布时间】:2011-06-25 12:08:32
【问题描述】:

我有这个 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");
}

然后抛出这个:

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

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

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

我有这个进口:

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

谢谢:)

【问题讨论】:

  • 如果已解决,则将答案标记为已接受。
  • 资源类型 PDDocument 没有实现 java.lang.AutoCloseable 所以我们不能在当前场景下尝试使用资源。
  • 也许您使用的是旧版本的 PDFBox。在 2.0.13 中,它是可关闭的,它扩展了 AutoCloseable。顺便说一句,这不是答案。

标签: java pdf pdfbox


【解决方案1】:

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

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

【讨论】:

  • 感谢 Jon Skeet,这段代码解决了 100% 的问题,感谢 :)
  • @Jon Skeet 我在 .net 编程中使用 pdfbox,我关闭了 'doc' 但错误仍然存​​在!我该怎么办?
  • @AmirHossein:听起来你应该问一个新问题。
【解决方案2】:

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

这是来自COSDocumentfinalize 方法:

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

要消除此警告,您应该在完成后显式调用文档上的close

【讨论】:

  • 谢谢dogbane,但我不知道我是否不明白你的回答。无论如何,我不在任何代码行中使用 COSDocument,所以我认为这不是问题... :)
  • @bonsai PDDocument.load 方法创建一个PDDocument,它有一个底层COSDocument。因此,您隐式使用了需要关闭的COSDocument。如果您关闭PDDocument,则底层COSDocument 也将关闭。
【解决方案3】:

也遇到了这个问题。使用 Java 7,您可以这样做:

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

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

【讨论】:

  • 顺便说一句,try-with-resources 自 Java 7 以来就存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
相关资源
最近更新 更多