编辑:在底部添加了 Java 8 try-with-resources 示例,因为该语言自最初发布以来已经发展。
如果您使用的是 Java 7(或更低版本),您发布的代码有两个问题:
- .close() 调用应该在 finally 块中处理。这样他们总是会被关闭,即使它在途中的某个地方掉进了一个捕获块。
- 您需要在其自己的 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
}
}