try(){}catch(){}

作者:斯巴拉西
链接:https://www.zhihu.com/question/41523613/answer/91339059
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

挺好用的语法,不用写一大堆finally来关闭资源,所有实现Closeable的类声明都可以写在里面,最常见于流操作,socket操作,新版的httpclient也可以;需要注意的是,try()的括号中可以写多行声明,每个声明的变量类型都必须是Closeable的子类,用分号隔开.楼上说不能关两个流的落伍了===补充一下,在没有这个语法之前,流操作一般是这样写的: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(
InputStream is = new FileInputStream(“…”);
OutputStream os = new FileOutputStream(“…”);
){
//…
}catch (IOException e) {
//…
}

例如:

try (final OutputStream os = response.getOutputStream()) {

        ExportUtil.responseSetProperties(fName, response);
        ExportUtil.doExport(dataList, sTitle, mapKey, os);
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("导出CSV失败", e);

    }

你可能感兴趣的:(java)