我正在使用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会帮我关闭这个流。是我做错了什么呢,还是这是意料之中的?我的代码似乎可以工作,但我不确定现在是否是关闭流的“正确时机”。
发布于 2018-02-02 14:13:02
使用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对象传递给open(),您将获得更好的性能。
发布于 2018-02-02 05:23:34
而不是这样:
COSDocument cospd = parser.getDocument();
return new PDDocument(cospd);试着这样做:
return parser.getPDDocument();https://stackoverflow.com/questions/48571808
复制相似问题