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

JAVA尝试关闭所有连接的有效方法是什么?,java,error-handling,io,try-catch,ioexception,Java,Error Handling,Io,Try Catch,Ioexception,例如,我有一种处理输入/输出流的方法: public void doSomethingWithStreams () throws FileNotFoundException, IOException { OutputStream out1, out2; InputStream in1, in2; try{ //do some

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

    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,它是有效的行为。 但如果我在这一行有例外:

 out1.close();
其他三个流将关闭。 你能推荐什么解决方案?怎么用?距离所有有多近

我只有一个:

    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块


您认为这是个好主意吗?

如果三条流彼此不依赖,则可能会让每条流的try/catch看起来更干净

比如:

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

{。。。。 }


编辑:正如iccthedral建议的,如果您使用Java7,您可以使用block。

最好的方法可能是:

try (
     OutputStream out1 = ...;
     OutputStream out2 = ...;
     InputStream in1 = ...;
     InputStream in2 = ...;
) {
     ...
}

也许最好的清理方法是制作如下方法:

public static void close(Closeable c) {
   if (c == null) return; 
   try {
       c.close();
   } catch (IOException e) {
       // Do anything or nothing
   }
}

这可以替换您的.close()调用,并且在调用失败时不会抛出异常。

或者更好地使用Java7,请尝试使用资源块。这可能是您的兴趣所在:请您做一个好公民,学习如何格式化代码,然后修复此问题中的格式设置。由于阅读困难,我几乎结束了这个问题。请看:谢谢。这是一个好的解决方案。@Chris,带有catch(IOException ex){//Do nothing}的解决方案是错误的解决方案!这是我的意见。@user471011是的,您可能不应该忽略异常。在一个严肃的项目中,你至少应该记录它们。这就是为什么我把
做任何事或什么都不做
的评论留在那里;由读者决定当流无法关闭时需要做什么。也许值得注意的是,它需要1.7+@assylias End of public for 1.6已推迟到2013年2月。你真的不想用这么短的生命周期来编写新代码。1.7是标准。
public static void close(Closeable c) {
   if (c == null) return; 
   try {
       c.close();
   } catch (IOException e) {
       // Do anything or nothing
   }
}