NcDreamy
NcDreamy

Reputation: 805

Deleting PDF file after printing in Java

I'm trying to delete a PDF file after printing. The PDF is generated using JAVA code and needs to be deleted after the printing process is carried out. However, I am facing an issue while deleting the file. I can't seem to figure out what the problem is.

The error shown while trying to delete the file from its folder is: "File in Use: The Action can't be completed because the file is open in Java(TM) Platform SE Binary."

The code I've used is as follows:

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;
}

Upvotes: 2

Views: 5975

Answers (1)

Scary Wombat
Scary Wombat

Reputation: 44834

why not put the deletion in a finally block?

} catch (Exception e) {
    e.printStackTrace();
} finally {
   if (file.exists()) {
    file.delete();
   }
}

After discussion with the OP, an approach was investigated to use Apache FileCleaningTracker whereby the File is tracked and then deleted after a Monitored Object has been GC'd.

Upvotes: 2

Related Questions