亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

關于java中流關閉的問題

關于java中流關閉的問題

白豬掌柜的 2019-03-13 14:14:01
有如下代碼:private static String extractContent(HttpResponse response) throws Exception {    String htmStr = null;    if (response.getStatusLine().getStatusCode() == 200) {        if (response != null) {            BufferedReader br = null;            InputStream ins = null;代碼中的br 和ins都正確的關閉掉了。但是在使用InputStreamReader的時候,是通過br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));來使用的,那么InputStreamReader是否需要顯示的關閉,即改成:private static String extractContent(HttpResponse response) throws Exception {    String htmStr = null;    if (response.getStatusLine().getStatusCode() == 200) {        if (response != null) {            BufferedReader br = null;            InputStream ins = null;            InputStreamReader inr = null;            try {                HttpEntity entity = response.getEntity();                ins = entity.getContent();                inr = new InputStreamReader(ins, "UTF-8");                br = new BufferedReader(inr);                StringBuffer sbf = new StringBuffer();                String line = null;                while ((line = br.readLine()) != null) {                    sbf.append(line);                }        我知道在JDK7之后提供了try with resources的方法解決了這種問題,但是在JDK7之前是不是必須的這樣用,顯示的分別new相應流對象,然后最后再關閉,而不能br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));像這樣嵌套這來用。我的問題:1.如果沒有流關閉,會帶來安全隱患,具體帶來何種安全隱患?最好能舉例說明。還有說沒有正確的關閉流,會造成系統資源的浪費,具體是指什么?(我的理解是浪費CPU資源,導致CPU輪詢去查詢是否有I/O傳輸,這樣的理解對不對啊)??2.jdk1.7之前,流的使用,是不是必須要用這種結構:BufferedReader ins = null;InputStreamReader inr = null;    try{        ins = ...        inr = ...    }catch{    ...    }finally{        if(null != ins) ins.close;        if(null != inr) inr.close;    }而不能使用這樣的結構:BufferedReader ins = null;    try{        ins = new InputStreamReader(new InputStrea(System.in, "UTF-8"));    }catch{    ...    }finally{        if(null != ins) ins.close;    }
查看完整描述

2 回答

  • 2 回答
  • 0 關注
  • 697 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號