7

我正在使用以下代码从与服务器的连接中关闭 InputStream 和 OutputStream:

try {
        if (mInputStream != null) {
            mInputStream.close();
            mInputStream = null;
        }

        if (mOutputStream != null) {
            mOutputStream.close();
            mOutputStream = null;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

然而,溪流并没有关闭,它们还活着。如果我再次连接,则有两个不同的 InputStream。该部分没有发现异常catch

我究竟做错了什么?

4

1 回答 1

19

编辑:在底部添加了 Java 8 try-with-resources 示例,因为该语言自最初发布以来已经发展。

如果您使用的是 Java 7(或更低版本),您发布的代码有两个问题:

  1. .close() 调用应该在 finally 块中处理。这样他们总是会被关闭,即使它在途中的某个地方掉进了一个捕获块。
  2. 您需要在其自己的 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
    }
}
于 2010-11-05T18:47:59.527 回答