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

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

BufferedReader關閉流的問題

BufferedReader關閉流的問題

慕慕森 2019-03-29 18:15:08
線上代碼,如何正確的關閉BufferedReader流。我用的JDK1.7原來的代碼如下:public static String httpPostWithJson(String ecUrl, String params) {        try {            // 創建連接            URL url = new URL(ecUrl);            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            connection.setDoOutput(true);            connection.setDoInput(true);            connection.setRequestMethod("POST");            connection.setUseCaches(false);            connection.setInstanceFollowRedirects(true);            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");            connection.connect();            // POST請求            DataOutputStream out = new DataOutputStream(connection.getOutputStream());            out.writeBytes(params);            out.flush();            out.close();            // 讀取響應            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));            String lines;            StringBuffer sb = new StringBuffer("");            while ((lines = reader.readLine()) != null) {                lines = new String(lines.getBytes(), "utf-8");                sb.append(lines);            }            // System.out.println(sb);            reader.close();            // 斷開連接            connection.disconnect();            return sb.toString();        } catch (MalformedURLException e) {            logger.error("httpPostWithJsonMalformedURLException error", e);            e.printStackTrace();        } catch (UnsupportedEncodingException e) {            logger.error("httpPostWithJsonUnsupportedEncodingException error", e);            e.printStackTrace();        } catch (IOException e) {            logger.error("httpPostWithJsonIOException error", e);            e.printStackTrace();        }        return null;    }這樣雖然在finally中關閉了流,但是又要在finally中引入IOException,這樣是不是很麻煩啊關于關閉流,還有沒有好的措施或者實踐經驗呢?謝謝~~補充:JDK 1.7但是不能用Try-with-resources機制
查看完整描述

4 回答

?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

這個問題其實無須過多困擾。也沒有必要往JDK1.7的try-with-resources上扯。
首先關閉資源放在try塊里一定會有問題:資源可能不被關閉。
所以資源的關閉應該放在finally里,這沒有什么疑問。
至于finally塊里close資源會額外引入IOE,這也是無法避免的。
目前(就我見到過的)絕大多數代碼里,捕獲IOE后,最多打一條log,更多的是noop,即no operations,do nothing。
close的時候IOE發生的幾率很小,它應該屬于一種操作系統層面的error,選擇忽略它是正確的選擇,畢竟你的系統不能因為一個資源關閉錯誤而停止運行。況且,如果你硬要捕獲這個IOE,那能做些什么呢。

如果不想在finally塊里引入try-catch,我見過guava的一種關閉方式,寫個工具方法叫做closeQuietly(),不吵不鬧就挺好。


查看完整回答
反對 回復 2019-04-21
?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

可以考慮Java7的try with resource


try (BufferedReader br = ...) {

    //...

} catch (IOException ex) {

    //...

}

參考


查看完整回答
反對 回復 2019-04-21
?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

同意1樓的答案,你補充的問題,也是由于IDE的問題。


另外對于實現了 AutoCloseable 和 Closeable 接口的資源,最好都使用 try-with-resources結構。


以你的代碼作為例子,省略了一些代碼


try{

    reader.readline();

}catch(IOException e){

    e.printStackTrace();

}finally {

    try {

       reader.close();

    } catch (IOException e) {

       e.printStackTrace();

    }

}

假設 readline 和 close 都發生io異常,使用 JDK1.7 前的異常捕捉結構,只能捕捉到 close 的異常,readline 的異常被抑制了。(因為 finally 的代碼必須執行)


另外一個問題,在 try-with-resources 中資源的 AutoCloseable 的 close 方法什么時候執行?


在執行完 try 代碼塊的代碼之后就會執行(這里不貼實驗代碼了),所以使用 try-with-resources 的結構,catch 塊和 finally 塊都是在資源進行關閉之后才會執行的。


查看完整回答
反對 回復 2019-04-21
  • 4 回答
  • 0 關注
  • 2146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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