java语言中try(){}catch(){}的用法介绍。介绍了通常的try…catch的用法以及 try-with-resources 的用法。
1、try{} catch(){}的用法
通常try/catch模块的用法是:
try{
// statement here
}catch(Exception e){
// deal with the exception
}finally {
// release the resources
}
先执行语句,包括打开关闭文件流等,然后在finally模块里关闭数据流。
但是最近碰到这样一种用法
try (InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target)){
byte[] buf = new byte[1024];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
}
这是一种 try-with-resources 的用法,称为 ARM (Automatic Resource Management) 自动资源管理。
2、try-with-resources的用法try(){}catch(){}
其基本语法是:
try(Resource resource = xxx) //可指定多个资源
{
//work with resource
}
其用法是:try(Resource resource = xxx)数据流xxx会在 try 执行完毕后自动被关闭,前提是,这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。
例如:
InputStream is = null;
OutputStream os = null;
try {
//...
} catch (IOException e) {
//...
}finally{
try {
if(os!=null){
os.close();
}
if(is!=null){
is.close();
}
} catch (IOException e2) {
//...
}
}
而用try-with-resources用法则简单的多:
try(
InputStream is = new FileInputStream("...");
OutputStream os = new FileOutputStream("...");
){
//...
}catch (IOException e) {
//...
}
其中的InputStream和OutputStream数据流会在try 执行完后自动关闭。一下简单多了。