1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        今日代碼 PK | 使用 try-with-resources 關(guān)閉資源

        共 2398字,需瀏覽 5分鐘

         ·

        2024-04-12 01:22

        try-with-resources 是 Java 7 中引入的一個語法糖,

        用于自動關(guān)閉實現(xiàn)了 AutoCloseable 或 Closeable 接口的資源,

        比如 文件輸入輸出流 等。

        使用try-with-resources關(guān)閉資源非常方便,

        示例代碼如下:

        try (InputStream in = new FileInputStream("input.txt");
             OutputStream out = new FileOutputStream("output.txt")) {
            // 處理輸入輸出流
        catch (IOException e) {
            e.printStackTrace();
        }

        如果不使用這種方式,那么就需要我們在 finally塊中手動處理,

        示例代碼如下:

        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream("input.txt");
            out = new FileOutputStream("output.txt");
            
            // 處理輸入輸出流
        catch (IOException e) {
            e.printStackTrace();
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        可以明顯的發(fā)現(xiàn),下面這種方式更加繁瑣,也容易出現(xiàn)遺漏關(guān)閉資源的情況。

        因此推薦大家使用try-with-resources方式來關(guān)閉資源。

        大家更喜歡哪種呢?歡迎投票并在評論區(qū)留下自己的想法。

        完整代碼片段來源于代碼小抄,歡迎點擊進(jìn)入小程序閱讀!

        在線訪問:https://www.codecopy.cn/post/umo6m1

        更多優(yōu)質(zhì)代碼歡迎進(jìn)入小程序查看!

        往期推薦

        今日代碼 PK | 避免循環(huán)查庫

        今日代碼 PK | 使用 Optional 判空

        今日代碼 PK | Java 使用正則表達(dá)式

        今日代碼 PK | 優(yōu)雅統(tǒng)計耗時

        今日代碼 PK | 日期時間處理

        瀏覽 41
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            做爱在线免费观看 | 青春草网站| 成人做爰黄A片免费看直播室动漫 | 国产精品久久久久久9999 | 肏屄片免费观看 | 免费看片18禁 | 免费国产裸播视频女主播 | 深夜福利电影网 | 久久人人爽人人爽人人片aV东京热 | 九九视频免费在线观看 |