try(){}catch(){}
作者:斯巴拉西
鏈接:https://www.zhihu.com/question/41523613/answer/91339059
來(lái)源:知乎
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
挺好用的語(yǔ)法,不用寫(xiě)一大堆finally來(lái)關(guān)閉資源,所有實(shí)現(xiàn)Closeable的類(lèi)聲明都可以寫(xiě)在里面,最常見(jiàn)于流操作,socket操作,新版的httpclient也可以;需要注意的是,try()的括號(hào)中可以寫(xiě)多行聲明,每個(gè)聲明的變量類(lèi)型都必須是Closeable的子類(lèi),用分號(hào)隔開(kāi).樓上說(shuō)不能關(guān)兩個(gè)流的落伍了===補(bǔ)充一下,在沒(méi)有這個(gè)語(yǔ)法之前,流操作一般是這樣寫(xiě)的: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) {
//…
}
}
而現(xiàn)在你可以這樣寫(xiě):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("導(dǎo)出CSV失敗", e);}總結(jié)
以上是生活随笔為你收集整理的try(){}catch(){}的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 微信小程序如何修改第三方组件样式 例如
- 下一篇: web登陆过程总结