My web application generates an XML file. I’m using a Struts2 stream result to manage the download, here’s the action in struts.xml:
<action name="generateXML" class="navigation.actions.GenerateXML">
<result type="stream">
<param name="contentType">text/xml</param>
<param name="inputName">inputStream</param>
<param name="bufferSize">1024</param>
</result>
...
</action>
Here’s the part of the action class “GenerateXML” where the FileInputStream “inputStream” is created:
public String execute() {
File xml = new File(filename);
...//fill the file with stuff
try {
setInputStream(new FileInputStream(xml));
} finally {
//inputStream.close();
xml.delete();
}
}
Deleting the file won’t work because the inputStream isn’t closed yet (That part is commented out). However, if i close it at this point the xml file downloaded by the user is empty since its stream was closed before struts generates the download.
Besides using a script that regularly deletes those temporary files on the server, is there a way to close “inputStream” AFTER struts has done its thing?
There isn’t a delete on close input stream, but you can write your own. See is there an existing FileInputStream delete on close?.
The idea is that you don’t pass a FileInputStream, but pass your ClosingFileInputStream, which overrides close and deletes the file when close is called. The close() will be called by struts:
See the linked question for more information.