2011-02-11 31 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()方法。