有如下代碼: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; }
添加回答
舉報
0/150
提交
取消