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.