4

我的 Web 应用程序生成一个 XML 文件。我正在使用 Struts2 流结果来管理下载,这是 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>

这是创建 FileInputStream“inputStream”的操作类“GenerateXML”的一部分:

public String execute() {
    File xml = new File(filename);
    ...//fill the file with stuff
    try {
        setInputStream(new FileInputStream(xml));
    } finally {
        //inputStream.close();
        xml.delete();
    }
}

删除文件将不起作用,因为 inputStream 尚未关闭(该部分已被注释掉)。但是,如果我此时关闭它,则用户下载的 xml 文件为空,因为它的流在 struts 生成下载之前已关闭。除了使用定期删除服务器上的那些临时文件的脚本之外,还有没有办法在 struts 完成它之后关闭“inputStream”?

4

2 回答 2

3

You need not do that. Struts2 will take care to close the steam itself all you need to do is to create a input stream and set it.

Here is how struts2 handle stream closing 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 stream is a result type in struts2 what it doing is that it picking the data from the stream you have defined flushing it and den closing it.

i hope it will clear your doubt.

于 2011-11-25T10:44:19.497 回答
3

关闭输入流没有删除,但您可以编写自己的。查看关闭时是否存在现有的 FileInputStream 删除?.

这个想法是你不传递 FileInputStream,而是传递你的 ClosingFileInputStream,它会覆盖 close 并在调用 close 时删除文件。close() 将被 struts 调用:

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

有关更多信息,请参阅链接的问题。

于 2011-11-25T10:27:10.377 回答