java - Java打印后删除PDF文件

标签 java pdf file-io itext

我正在尝试在打印后删除 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/

相关文章:

java - spring Bean 创建异常 Error creating bean with name

java - 如何测试采用 Class<T> 的方法

iphone - 从 PDF 中提取图像

c - 从c中的文件中读取固定大小的行

java - 在具有 AMD 处理器的计算机上运行 Android 模拟器

java - java反射(处理)中的奇怪错误

c# - 如何将 pdf 转换为 .net 中的位图图像?

android:使用内置的 pdf 查看器从我的应用程序中打开一个 pdf

matlab - 从文本文件中将数据读入 MATLAB

c# - 如何在同一个文件中优雅地实现多个字符串替换?