Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there an existing FileInputStream delete on close?

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 FileInputStreamand 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.

like image 421
Shawn D. Avatar asked Jan 14 '11 17:01

Shawn D.


People also ask

Is it necessary to close FileInputStream?

Yes, you need to close the inputstream if you want your system resources released back. FileInputStream. close() is what you need.

What is the difference between FileReader and FileInputStream?

FileInputStream is Byte Based, it can be used to read bytes. FileReader is Character Based, it can be used to read characters. FileInputStream is used for reading binary files. FileReader is used for reading text files in platform default encoding.

How do I delete a Fileoutputstream in Java?

File f = new File("MY_TEMP. TXT"); f. delete();

Which exception is thrown by FileInputStream?

The FileInputStream read() method throws a java. io. IOException if for some reason it can't read from the file. Again, the InputFile class makes no attempt to catch or declare this exception.


1 Answers

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;          }        }    } } 
like image 112
nos Avatar answered Sep 22 '22 08:09

nos