应该如何一个InputStream和一个OutputStream被关闭? [英] How should an InputStream and an OutputStream be closed?

查看:990
本文介绍了应该如何一个InputStream和一个OutputStream被关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code从到服务器的连接,关闭一个InputStream和一个OutputStream:

I'm using the following code to close an InputStream and an OutputStream from a connection to a server:

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

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

不过,流不关闭,他们还活着。如果我再次连接有两种不同的InputStreams。无例外被夹在部分。

我在做什么错了?

推荐答案

两个问题你贴code:

Two problems with your posted code:


  1. 的.close()调用应该在finally块来处理。这样,他们将永远是封闭的,即使它一路下跌到catch块的地方。

  2. 您需要处理在自己的try / catch块中的每个.close()调用或者你可以离开他们的一个搁浅开放。如果你试图关闭输入流失败,你会被跳过试图关闭输出流。

您希望像这样的东西更多:

You want something more like this:

    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
            }
        }
    }

这篇关于应该如何一个InputStream和一个OutputStream被关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆