我使用以下代码来关闭与服务器的连接的 InputStream 和 OutputStream:
try {
if (mInputStream != null) {
mInputStream.close();
mInputStream = null;
}
if (mOutputStream != null) {
mOutputStream.close();
mOutputStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
然而,溪流并没有关闭,它们仍然活着。如果我再次连接,则会有两个不同的输入流。无一例外地被捕获catch
部分。
我究竟做错了什么?
编辑:在底部添加了 Java 8 try-with-resources 示例,因为该语言自最初发布以来已经不断发展。
如果您使用的是 Java 7(或更低版本),则您发布的代码存在两个问题:
- .close() 调用应该在finally 块中处理。这样它们将始终被关闭,即使它在途中的某个地方落入了 catch 块。
- 您需要在其自己的 try/catch 块中处理每个 .close() 调用,否则您可能会使其中一个处于打开状态。如果您尝试关闭输入流失败,您将跳过关闭输出流的尝试。
你想要更多这样的东西:
InputStream mInputStream = null;
OutputStream mOutputStream = null;
try {
mInputStream = new FileInputStream("\\Path\\MyFileName1.txt");
mOutputStream = new FileOutputStream("\\Path\\MyFileName2.txt");
//... do stuff to your streams
}
catch(FileNotFoundException fnex) {
//Handle the error... but the streams are still open!
}
finally {
//close input
if (mInputStream != null) {
try {
mInputStream.close();
}
catch(IOException ioex) {
//Very bad things just happened... handle it
}
}
//Close output
if (mOutputStream != null) {
try {
mOutputStream.close();
}
catch(IOException ioex) {
//Very bad things just happened... handle it
}
}
}
如果您使用的是 Java 8+,则不需要任何 catch/finally 噪音。您可以使用 try-with-resources 语法,无论您何时以何种方式离开该块,Java 都会为您关闭资源:
try(InputStream mInputStream = new FileInputStream("\\Path\\MyFileName1.txt")) {
try(OutputStream mOutputStream = new FileOutputStream("\\Path\\MyFileName2.txt")) {
//... do stuff to your streams
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)