应如何关闭InputStream和OutputStream?

moo*_*cle 5 android inputstream outputstream

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

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

        if (mOutputStream != null) {
            mOutputStream.close();
            mOutputStream = null;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

然而,溪流没有关闭,他们仍然活着.如果我再次连接,则有两个不同的InputStream.该catch部分没有例外.

我究竟做错了什么?

Sky*_*ton 18

您发布的代码有两个问题:

  1. 应该在finally块中处理.close()调用.通过这种方式,它们总是会被关闭,即使它在沿途的某个地方掉进了一个挡块.
  2. 你需要在自己的try/catch块中处理EACH .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
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)