Java的.尝试关闭所有连接的有效方法是什么?

use*_*011 3 java io error-handling try-catch ioexception

例如,我有处理输入/输出流的方法:

    public void doSomethingWithStreams () throws FileNotFoundException, IOException
            {
             OutputStream out1, out2;            
             InputStream in1, in2;
try{                     
            //do something with Streams: read, write, process, etc.
            }
finally{
        //There I try to close connections
        out1.close();
        out2.close();
        in1.close();
        in2.close();
        }    
            }
Run Code Online (Sandbox Code Playgroud)

方法可以抛出IOException并且它是有效的行为.但如果我在这行中有异常:

 out1.close();
Run Code Online (Sandbox Code Playgroud)

其他三个Stream将不会关闭.你能推荐什么解决方案?怎么样?如何关闭所有

我只有一个:

    public void doSomethingWithStreams () throws FileNotFoundException, IOException
            {
             OutputStream out1, out2;            
             InputStream in1, in2;
         try{            
            //do something with Streams: read, write, process, etc.
            }
finally{
        //There I try to close connections

try{out1.close();}
  finally{
     try{out2.close();}
         finally{
            try{in1.close();}
                finally{
        in2.close();}
}}

}

            }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的 - 我的方法是使用多个try-finally块.

你认为这是好主意吗?

kos*_*osa 6

如果三个流不相互依赖,则可能对每个流看起来更清洁.

就像是:

try{
 out1.close();
}catch(Exception e)
{
....
}finally
Run Code Online (Sandbox Code Playgroud)

{....}

try{
        out2.close();
}catch(Exception e)
{
.....
}finally
Run Code Online (Sandbox Code Playgroud)

{....}

编辑:作为iccthedral建议,如果您使用Java7,您可以使用try-with-resource块.

  • 或者甚至更好地使用Java7 try-with-resource块. (3认同)