使用PdfBox后,我无法删除pdf文件。所有可关闭的变量均已关闭,但无济于事。使用PdfBox库的应用启动方法时,无论如何都无法删除pdf文件。
public void generateTxtFromPDF(String txtFile, String pdfFile) throws IOException {
COSDocument cosDoc = null;
PDDocument document = null;
PrintWriter pw = null;
try {
File f = new File(pdfFile);
String parsedText;
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
parser.parse();
cosDoc = parser.getDocument();
PDFTextStripper pdfStripper = new PDFTextStripper();
document = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(document);
pw = new PrintWriter(txtFile);
pw.print(parsedText);
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
if (document != null) {
try {
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (cosDoc != null) {
cosDoc.close();
}
}
}
也许有人知道出什么问题了吗
答案 0 :(得分:0)
我已解决此问题-更改JDK版本(jdk1.8.0_181 => jdk1.8.0_221)。感谢您对我的问题的关注。并使用以下代码:
public void generateTxtFromPDF(String txtFile, String pdfFile) throws IOException {
File f = new File(pdfFile);
String parsedText;
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
parser.parse();
PDDocument document = null;
try (PrintWriter pw = new PrintWriter(txtFile);
COSDocument cosDoc = parser.getDocument()) {
document = new PDDocument(cosDoc);
PDFTextStripper pdfStripper = new PDFTextStripper();
parsedText = pdfStripper.getText(document);
pw.print(parsedText);
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
} finally {
document.close();
document = null;
}
}