Java关闭PDF错误

我有这个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:

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

谢谢 :)

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

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

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

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

由于PDDocument implements Closeable ,因此try块将在结束时自动调用其close()方法。

当pdf文档最终确定并且尚未关闭时,将发出此警告。

以下是COSDocument的finalize方法:

 /** * 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