search

Home  >  Q&A  >  body text

Java的HttpURLConnecction的getInputStream是否需要close?

RT,就酱
Java的HttpURLConnecction的getInputStream是否需要close?

这个流是否是系统维护的?
因为不是我打开的

迷茫迷茫2802 days ago497

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 10:51:55

    Get into the habit of closing all InputStreams and OutputStreams that are no longer in use, regardless of whether the implementation behind the API automatically closes them for you.
    If written in Java 1.7+, it is very simple to use try-with-resource:

    try (InputStream in = urlConnection.getInputStream()) {
        ...
    } // 这里会自动调用 in.close();
    

    Similar scenes include:

    • JDBC’s PreparedStatement, ResultSet, etc. all implement the AutoCloseable interface. In theory, as long as the Connection is closed, the PreparedStatement, ResultSet, etc. generated by it will also be automatically closed. However, it is strongly recommended that you use try-with when generating these resources. -resource to manage.

    • The same goes for resources such as getInputStream/getOutputStream in ServletRequest/ServletResponse.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:51:55

    Need

    In the case of very high concurrent operations, if you do not close it, the overhead on system resources will be relatively large.

    reply
    0
  • Cancelreply