我正在尝试在打印后删除 PDF 文件。 PDF是使用JAVA代码生成的,在执行打印过程后需要删除。但是,我在删除文件时遇到问题。我似乎无法弄清楚问题出在哪里。
尝试从文件夹中删除文件时显示的错误是: “文件正在使用:该操作无法完成,因为该文件已在 Java(TM) Platform SE Binary 中打开。”
我使用的代码如下:
public String actionPrintReport() {
try {
// Creates a new document object
Document document = new Document(PageSize.LETTER);
File file = new File(fileLocation.concat("\\".concat(fileName)));
FileOutputStream fo = new FileOutputStream(file);
// Creates a pdfWriter object for the FILE
PdfWriter pdfWriter = PdfWriter.getInstance(document, fo);
// Open the document
document.open();
// Add meta data...
// Insert Data...
// Close the document
document.close();
// Create a PDFFile from a File reference
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
PDFFile pdfFile = new PDFFile(bb);
// Create PDF Print Page
PDFPrintPage pages = new PDFPrintPage(pdfFile);
// Create Print Job...
// Close
fo.flush();
fo.close();
fis.close();
if (file.exists()) {
if (file.delete()) {
String check = "yes";
} else {
String check = "no";
}
}
// Send print job to default printer
pjob.print();
actionMsg = "success";
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
}
return ERROR;
}
最佳答案
为什么不将删除放在finally block 中?
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file.exists()) {
file.delete();
}
}
与OP讨论后,研究了一种使用Apache FileCleaningTracker的方法由此,在受监控对象被 GC 后,文件将被跟踪并删除。
关于java - Java打印后删除PDF文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24051538/