【问题标题】:How should an InputStream and an OutputStream be closed?InputStream 和 OutputStream 应该如何关闭?
【发布时间】:2011-05-05 17:26:51
【问题描述】:

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

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

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

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

我做错了什么?

【问题讨论】:

  • 不管没有抛出异常,您都应该将 close 语句放在 finally 块中,以便您的流始终正确关闭(异常与否)。
  • “流仍然存在”是什么意思?
  • 在调用 close 方法后,流仍在从服务器接收数据。当我关闭应用程序时,连接已关闭。 ^^;;;
  • @moongcle:您的流不是“仍在从服务器接收数据”。流不与服务器对话。套接字与服务器通信。

标签: android inputstream outputstream


【解决方案1】:

编辑:在底部添加了 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
    }
}

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 2012-08-03
    • 2016-08-20
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多