2016-02-29 19 views
0

閱讀我讀從PDF文件從Java

try { 
    File pdfFile = new File("ffile.pdf"); 
    PDFParser parser = new PDFParser(new FileInputStream(pdfFile));  
    parser.parse(); 
    COSDocument cosDoc = parser.getDocument(); 
    PDFTextStripper pdfStripper = new PDFTextStripper(); 
    PDDocument pdDoc = new PDDocument(cosDoc); 
    //do sth 

} catch (Exception e) { 
    System.err.println("An exception occured in parsing the PDF Document." 
        + e.getMessage()); 
} 

有的時候一些文本關閉一個PDF文件,我得到這個錯誤:

WARNING [Finalizer] org.apache.pdfbox.cos.COSDocument.finalize Warning: You did not close a PDF Document 

我在這兒,看一個類似的qustion它說我必須關閉打開的文件。所以,我加

finally{ 
    pdfFile.close(); //<- 
} 

但Netbeans標記錯誤close()說無法找到符號。 那我要結束什麼?我也試過parser.close(),但這行也是從Netbeans標記爲錯誤的。

+0

你試圖關閉什麼,你在你的代碼中給了它什麼名字? – Stultuske

+0

我想關閉我加載的文件,這是'pdfFile' – yaylitzis

+1

您需要關閉COSDocument,而不是解析器。 – bmargulies

回答

1

使用PDDocumentclose()方法或COSDocument實例(在兩種情況下COSDocument對象的close方法被調用)

+0

你的意思是'cosDoc.close();' – yaylitzis

+0

@ Nat95:這將是使用的代碼。我想我需要重新解釋答案... – fabian

2

您正在使用過期的方式打開文件。這是正確的方法(省略異常處理):

File pdfFile = new File("ffile.pdf"); 
PDDocument pdDoc = PDDocument.load(pdfFile); 
PDFTextStripper pdfStripper = new PDFTextStripper(); 
//.... 
pdDoc.close(); 
+0

簡單得多又簡單! –