Java。尝试关闭所有连接的有效方法是什么? [英] Java. What is the valid way try to close all connections?

查看:75
本文介绍了Java。尝试关闭所有连接的有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有使用输入/输出流的方法:

For example, I have method for working with input/output streams:

    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();
        }    
            }

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

Method can throws IOException and it is valid behavior. But If I have Exception in this line:

 out1.close();

其他三个流将关闭。
您可以推荐什么解决方案?怎么样? 全部有多近?

others three Stream will be NOT closed. What solution can you recommend? How? How close all?

我只有一个:

    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();}
}}

}

            }

如您所见-我的方法是使用多个try-finally块。

As you can see - my approach is using multiple try-finally blocks.

您认为这是个好主意吗?

Do you think it is good idea?

推荐答案

如果三个流彼此不依赖,则可以尝试一下/ catch,让每个流看起来更干净。

If three streams are not dependent on each other, may be having try/catch for each stream look cleaner.

类似的东西:

try{
 out1.close();
}catch(Exception e)
{
....
}finally

{....
}

{.... }

try{
        out2.close();
}catch(Exception e)
{
.....
}finally

{....
}

{.... }

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

As iccthedral suggested, if you use Java7 you may use try-with-resource block.

这篇关于Java。尝试关闭所有连接的有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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