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.
Yes, you need to close the inputstream if you want your system resources released back. FileInputStream. close() is what you need.
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.
File f = new File("MY_TEMP. TXT"); f. delete();
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.
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; } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With