应该如何关闭InputStream和OutputStream?
我使用以下代码来关闭与服务器的连接的输入流和输出流:
try {
if (mInputStream != null) {
mInputStream.close();
mInputStream = null;
}
if (mOutputStream != null) {
mOutputStream.close();
mOutputStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
但是,流并未关闭,它们仍然存在。如果我再次连接,则会有两个不同的输入流。 catch
部分没有捕获任何异常。
我做错了什么?
I'm using the following code to close an InputStream and an OutputStream from a connection to a server:
try {
if (mInputStream != null) {
mInputStream.close();
mInputStream = null;
}
if (mOutputStream != null) {
mOutputStream.close();
mOutputStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
However, the streams are not closing, they are still alive. If I connect again there are two different InputStreams. No exception is being caught in the catch
section.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:在底部添加了 Java 8 try-with-resources 示例,因为该语言自最初发布以来已经不断发展。
如果您使用的是 Java 7(或更低版本),则您发布的代码存在两个问题:
您想要的更像是这样的:
如果您使用的是 Java 8+,则不需要任何 catch/finally 噪音。您可以使用 try-with-resources 语法,无论您何时以何种方式离开该块,Java 都会为您关闭资源:
Edit: Added the Java 8 try-with-resources example at the bottom, since the language has evolved since originally posted.
If you are using Java 7 (or lower), there are two problems with your posted code:
You want something more like this:
If you are using Java 8+, you don't need any of the catch/finally noise. You can use the try-with-resources syntax and Java will close the resource for you whenever and however you leave the block: