2010-11-05 51 views
4

我使用下面的代码从一个服务器的连接关闭一个InputStream和一个OutputStream: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

不管事实是一个异常没有被抛出,你应该把接近语句finally块,这样你流将始终正确关闭(例外或不)。 – McStretch 2010-11-05 17:12:04

+0

“溪流还活着”是什么意思? – 2010-11-05 17:15:46

+0

在调用close方法之后,流仍然从服务器接收数据。当我关闭应用程序时,连接关闭。 ^^ ;;; – mooongcle 2010-11-05 17:19:45

回答

15

两个问题,你的发布代码:

  1. ()调用应该在处理finally块的.close。这样他们总是会被关闭,即使它在某个方向上掉进了一个捕获块。
  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 
      } 
     } 
    } 
相关问题