yaylitzis
yaylitzis

Reputation: 5534

Close a PDF file when read it from java

I am reading some text from a pdf file

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

and some times I get this error:

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

I read a similar qustion here where it says I have to close the opened file. So, I added

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

but Netbeans mark it with error the close() saying that can't find symbol. So what I have to close? I tried also parser.close() but this line is also marked with error from Netbeans.

Upvotes: 0

Views: 4454

Answers (2)

Tilman Hausherr
Tilman Hausherr

Reputation: 18851

You are using an outdated way to open files. This is the correct way to do it (exception handling omitted):

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

Upvotes: 2

fabian
fabian

Reputation: 82461

Use the close() method of the PDDocument or the COSDocument instance (in both cases the close method of the COSDocument object is called)

Upvotes: 1

Related Questions