在 PDFBox 的 PDFParser 中关闭 Stream 的正确方法

Proper way to close Stream in PDFParser in PDFBox

我正在使用 pdfbox2.0.3 解析 PDF 文档:

private PDDocument getPDDocument(InputStream inputStream) throws IOException {
    org.apache.pdfbox.pdfparser.PDFParser parser = new org.apache.pdfbox.pdfparser.PDFParser(
            new RandomAccessBufferedFileInputStream(inputStream));

    try {
        parser.parse();
    } catch (NoClassDefFoundError e) {
        throw new SecurityException("PDF document is protected.", e);
    }

    COSDocument cospd = parser.getDocument();
    return new PDDocument(cospd);
}

稍后我关闭文档进行清理:

pd.close();

我意识到这会在我的文件夹中留下一个未清理的临时文件。玩了之后,我意识到我必须专门关闭 RandomAccessBufferedFileInputStream。

private PDDocument getPDDocument(InputStream inputStream) throws IOException {
    RandomAccessBufferedFileInputStream strm = new RandomAccessBufferedFileInputStream(inputStream);

    try {
        org.apache.pdfbox.pdfparser.PDFParser parser = new org.apache.pdfbox.pdfparser.PDFParser(strm);

        try {
            parser.parse();
        } catch (NoClassDefFoundError e) {
            throw new SecurityException("PDF document is protected.", e);
        }

        COSDocument cospd = parser.getDocument();
        return new PDDocument(cospd);
    } finally {
        strm.close();
    }
}

我有点期待 PDDocument 或 COSDocument 为我关闭此流。我做错了什么还是这是预期的?我的代码似乎有效,但我不确定这是否是关闭流的 "right time"。

而不是这个:

   COSDocument cospd = parser.getDocument();
   return new PDDocument(cospd);

尝试这样做:

return parser.getPDDocument();

使用 PDFBox 2.* 的正确方法是:

private PDDocument getPDDocument(InputStream inputStream) throws IOException
{
    return PDDocument.load(inputStream);
}

关闭文档的正确方法是

doc.close();

doc 是一个 PDDocument 对象。

当前版本是2.0.8。

另一个好的工作模式是用打开文档的相同方法关闭文档,这样你就可以使用JDK7的try-with-resources。

如果您的 InputStream 来自文件,那么您可以并且应该将 File 对象传递给 open(),您将获得更好的性能。