天天看點

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);

    }