2011-02-11 125 views
6

我有这样的Java代码:Java的紧密PDF错误

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; 

谢谢:)

+0

如果解决了问题,则将答案标记为已接受。 – skaffman 2011-02-14 08:38:11

回答

11

你加载PDDocument但不能关闭它。我怀疑你需要这样做:

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

感谢Jon Skeet,这段代码解决了100%的问题,谢谢:) – bonsai 2011-02-14 08:27:35

+0

@Jon Skeet我在.net编程中使用pdfbox,我关闭'doc'但错误仍然存​​在!我能做什么? – AmirHossein 2013-07-23 17:15:38

+0

@AmirHossein:听起来你应该问一个新问题。 – 2013-07-23 17:38:57

4

这个警告是在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当你用它做。

6

刚刚也有这个问题。在Java 7,你可以这样做:

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

因为PDDocument implements Closeable,该try块将自动地拨打结束其close()方法。