Raja D
Raja D

Reputation:

Image not deleted even if file.delete() method is called

I need to send an email along with an embedded image. Once the email has been sent, the image in the application server should be deleted immediately. The problem I'm facing is, after the email is sent, the control goes method which contain,

File file = new File("../bar.jpeg")
if(file.exists()){
  file.delete();
  System.out.println("Barcode Image Deleted");
}

It's printing "Barcode Image Deleted". But, the image is not deleted and is still present in the same location. I'm using multipart to attach the image to the email.

Why is it not getting deleted?

Upvotes: 2

Views: 4569

Answers (4)

Stephen Denne
Stephen Denne

Reputation: 37027

Are you using javax.mail?
If so, you'll need to wait till the mail has finished being sent, which you find out about by registering a TransportListener.

This also means you won't be able to use the static Transport.send() methods, but will have to construct and clean up your own session and transport.

I'm trying to remember details from a while ago... I think the DataHandler or DataSource don't close the input stream when they've finished reading it, so you need to keep a reference to it and close it yourself before you can delete the underlying file.

Upvotes: 8

Stu Thompson
Stu Thompson

Reputation: 38898

Firstly, File.delete() returns a boolean if it successfully deletes a file. Check that value and at least log it.

If it is not being deleted, then I would guess that either

  1. the file is currently open for reading and the OS won't let you delete it until it is closed. Possible your mail software? My guess is that the mail software does not try to base64 encode the image (for inclusion in the message) until it is actually sending the message...and/or does not stop reading it until the mail is sent.
  2. the java process does not have permissions to delete the file

Upvotes: 3

coobird
coobird

Reputation: 160992

The File.delete method returns a boolean which indicates whether the deletion was successful.

It could be that the file deletion is not being successfully performed due to not having permissions to delete the file.

Upvotes: 6

tschaible
tschaible

Reputation: 7695

File.delete() returns a true/false condition. Try checking the return condition of delete to see if the system is actually reporting the file as deleted.

Upvotes: 3

Related Questions