Closing URLConnection and InputStream correctly?

后端 未结 2 1745
轮回少年
轮回少年 2020-12-14 14:23

I\'ve seen many different examples of using HttpURLConnection + InputStream, and closing them (or not closing them) after use. This is what I came up with to make sure every

相关标签:
2条回答
  • 2020-12-14 14:50

    There is also the new (with Java 7) 'try()' technique

            try (OutputStream os = http.getOutputStream()) {
                os.write(out);
            }
    

    Basically, it will auto-close anything in the try() statement, regardless of whether it is successful or not.

    0 讨论(0)
  • 2020-12-14 14:54

    Yep.. Doing the end part in finally would be best idea because if code fails somewhere, program won't reach till .close(), .disconnect() statements that we keep before catch statements...

    If the code fails somewhere and exception is thrown in between of the program, still finally get executed regardless of exception thrown...

    0 讨论(0)
提交回复
热议问题