Closing FileInputStream used by struts stream result

My web application is creating an XML file. I use the result of the Struts2 stream to control loading, here is 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> 

This creates the part of the "GenerateXML" action class, where the "inputStream" FileInputStream 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 a file will not work because inputStream is not closed yet (this part is commented out). However, if I close it at this moment, the xml file uploaded by the user is empty, since its stream was closed before struts generates the download. Besides using a script that regularly deletes these temporary files on the server, is there a way to close the "inputStream" AFTER struts did their job?

+4
source share
2 answers

There is no deletion in a closed input stream, but you can write your own. See is there an existing FileInputStream deletion on close? .

The idea is that you are not passing FileInputStream, but passing your ClosingFileInputStream, which overrides the closure and deletes the file when close is called. The close () function will be called struts:

 public String execute() { File xml = new File(filename); ...//fill the file with stuff setInputStream(new ClosingFileInputStream(xml)); } 

See the related question for more information.

+3
source

You do not need to do this. Struts2 will take care to close the steam, all you have to do is create an input stream and install it.

This is how struts2 handles the thread for you

 public class StreamResult extends StrutsResultSupport { // removing all other code { // Flush oOutput.flush(); } finally { if (inputStream != null) inputStream.close(); if (oOutput != null) oOutput.close(); } } 

So, since the stream is a result type in struts2, it does what it collects data from the stream that you defined to clear it and then close it.

I hope this clears your doubts.

+2
source

Source: https://habr.com/ru/post/1383029/


All Articles