让代码看上去优雅一些
作者:王宏江
安全的关闭一个流,一般是用finally来实现的。
Reader reader = null;
OutputStream os = null;
try{
reader = createReader();
reader.read();
os = createOuputStream();
os.write();
doSomething();
}catch(IOException ioe){
handleException();
}
finally{
try{
if (reader != null)
reader.close();
if (os != null)
os.close();
}catch(IOException e){
}
}
在java5之前,这种写法显得finally块中臃肿难看。
在java5中增加了一些新的功能和接口,可以更加优雅的实现对流的关闭。
Closeable接口:
所有的流都实现了此接口,因此可以用一个通用的函数来代替上面finally块中的代码。
public static void close(Closeable stream)
{
if (stream != null)
{
try{
stream.close();
}catch(IOException ioe){
}
}
}
这样可以关闭流的时候只需要在finally块中调用这个函数即可。可以把它放到一个工具类中。
而有的时候,会用到很多的流,要一一关闭,需要一一调用。
这时可以使用java5中的变长参数的新功能来实现的更优雅一些:
public static void close(Closeable... streams)
{
try
{
for(Closeable s : streams)
{
if (s != null)
s.close();
}
}catch(IOException ioe)
{
}
}
这样在finally块中可以用这样的方式来进行:
try{
//do();
}catch(Exception e){
}
finally{
IOStreamUtil.close(stream1, stream2, stream3,stream4);
}
 
 
 
公司网站:www.chundi.com 邮件技术支持网站:www.mailer.com.cn  短信技术支持网站:www.sendsms.cn
Copyright 1997-2017 北京春笛信息技术有限公司 地址:北京海淀区知春路23号863软件园量子银座九层