Java закрыть PDF ошибка - PullRequest
       15

Java закрыть PDF ошибка

7 голосов
/ 11 февраля 2011

У меня есть этот код 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 org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

Спасибо:)

Ответы [ 3 ]

13 голосов
/ 11 февраля 2011

Вы загружаете PDDocument, но не закрываете его. Я подозреваю, что вам нужно сделать:

String textOfPdf;
PDDocument doc = PDDocument.load("doc");
try {
    textOfPdf = pdfs.getText(doc);
} finally {
    doc.close();
}
7 голосов
/ 06 июля 2015

Только что тоже была эта проблема. С Java 7 вы можете сделать это:

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

Поскольку PDDocument implements Closeable, блок try автоматически вызовет свой метод close() в конце.

4 голосов
/ 11 февраля 2011

Это предупреждение выдается, когда документ PDF завершен и не был закрыт.

Вот метод finalize из COSDocument :

/**
 * 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 в документе, когда вы закончите с ним.

...