is there an existing FileInputStream delete on close?

file-io, java, temporary-files

Solution

There's no such thing in the standard libraries, and not any of the apache-commons libs either , so something like:

public class DeleteOnCloseFileInputStream extends FileInputStream {
   private File file;
   public DeleteOnCloseFileInputStream(String fileName) throws FileNotFoundException{
      this(new File(fileName));
   }
   public DeleteOnCloseFileInputStream(File file) throws FileNotFoundException{
      super(file);
      this.file = file;
   }

   public void close() throws IOException {
       try {
          super.close();
       } finally {
          if(file != null) {
             file.delete();
             file = null;
         }
       }
   }
}

Problem

Is there an existing way to have a `FileInputStream` delete the underlying file automatically when closed? I was planning to make my own utility class to extend `FileInputStream`and do it myself, but I'm kinda surprised that there isn't something already existing. edit: Use case is that I have a Struts 2 action that returns an `InputStream` for file download from a page. As far as I can tell, I don't get notified when the action is finished, or the `FileInputStream` is not in use anymore, and I don't want the (potentially large) temporary files that are generated to be downloaded left lying around. The question wasn't Struts 2 specific, so I didn't include that info originally and complicate the question.

Original source