Java 我应该关闭 servlet 输出流吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1829784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:02:53  来源:igfitidea点击:

Should I close the servlet outputstream?

javaservlets

提问by leeeroy

Possible Duplicate:
Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?

可能的重复:
应该在 HttpServletResponse.getOutputStream()/.getWriter() 上调用 .close() 吗?

Am I responsible for closing the HttpServletResponse.getOutputStream() (or the getWriter() or even the inputstream) or should I leave it to the container ?

我是负责关闭 HttpServletResponse.getOutputStream() (或 getWriter() 甚至输入流)还是应该将它留给容器?

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException {
    OutputStream o = response.getOutputStream();
    ... 
    o.close(); //yes/no ?
}

采纳答案by BalusC

You indeed don't need to do so.

你确实不需要这样做。

Thumb rule: if you didn't create/open it yourself using new SomeOutputStream(), then you don't need to close it yourself. If it was for example a new FileOutputStream("c:/foo.txt"), then you obviously need to close it yourself.

经验法则:如果您没有使用 自己创建/打开它new SomeOutputStream(),那么您不需要自己关闭它。如果它是例如 a new FileOutputStream("c:/foo.txt"),那么您显然需要自己关闭它。

Reasons that some people still do it are just to ensurethat nothing more will be written to the response body. If it would ever happen, then this will cause an IllegalStateExceptionin the appserver logs, but this wouldn't affect the client, so the client still gets the proper response. This is also an easier debug to spot the potential problems in the request-response chain which you wouldn't see at first glance. For example, something else is appending more data to the response body somewhere further down in the chain.

有些人仍然这样做的原因只是为了确保不会将更多内容写入响应主体。如果它会发生,那么这将导致IllegalStateException应用服务器日志中出现异常,但这不会影响客户端,因此客户端仍然会得到正确的响应。这也是一种更容易的调试,可以发现请求-响应链中您第一眼看不到的潜在问题。例如,其他东西正在将更多数据附加到响应链中更靠后的某个位置。

Another reason which you see among starters is that they just wanted to preventthat more data is written to the response body. You see this often when JSP incorrectly plays a role in the response. They just ignore the IllegalStateExceptions in the logs. Needless to say that this particular purpose is bad.

您在初学者中看到的另一个原因是,他们只是想防止将更多数据写入响应正文。当 JSP 在响应中错误地发挥作用时,您经常会看到这种情况。他们只是忽略IllegalStateException日志中的s。不用说,这个特殊目的是不好的

回答by Jeremy Raymond

No you don't need to close it. If you do you basically end the response to the client. After closing the stream you cannot send anything else to the client until the next request. You didn't open the stream, so you don't have to close it.

不,你不需要关闭它。如果你这样做,你基本上会结束对客户端的响应。关闭流后,在下一个请求之前,您无法向客户端发送任何其他内容。您没有打开流,因此您不必关闭它。