我打算在打印后删除PDF文件。 PDF是使用JAVA代码生成的,需要在执行打印过程后删除。但是,我在删除文件时遇到问题。我似乎无法弄清问题是什么。
尝试从文件夹中删除文件时显示的错误是: &#34;正在使用的文件:由于文件在Java(TM)平台SE二进制文件中打开,因此无法完成操作。&#34; < / p>
我使用的代码如下:
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;
}
答案 0 :(得分:2)
为什么不把删除放在finally块中?
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file.exists()) {
file.delete();
}
}
在与OP讨论之后,调查了一种方法,使用Apache FileCleaningTracker来跟踪文件,然后在监视对象已经过GC后删除。