【问题标题】:Closing a FileInputStream used by struts' stream result关闭 struts 的流结果使用的 FileInputStream
【发布时间】:2011-11-25 10:10:31
【问题描述】:

我的 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”?

【问题讨论】:

  • Matthew 的参考书很不错。另一种选择是在invoke() 之后的拦截器中进行文件清理。这可能更具可定制性,尽管在这种情况下可能无关紧要。

标签: java struts2 download struts fileinputstream


【解决方案1】:

关闭输入流时没有删除,但您可以自己编写。见is there an existing FileInputStream delete on close?

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

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

有关详细信息,请参阅链接的问题。

【讨论】:

    【解决方案2】:

    你不必那样做。 Struts2 会自动关闭 Steam,您需要做的就是创建一个输入流并设置它。

    这是 struts2 如何为您处理流关闭

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

    因此,由于流是 struts2 中的结果类型,它所做的就是从您定义的流中提取数据并刷新它并关闭它。

    我希望它能消除你的疑问。

    【讨论】:

    • 问题是,在 Struts 完成后,我无法再控制使用该流的文件,所以我无法删除它。 Matthew 的解决方案奏效了。
    猜你喜欢
    • 2017-02-06
    • 1970-01-01
    • 2010-09-14
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    相关资源
    最近更新 更多