<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          今日代碼 PK | 使用 try-with-resources 關閉資源

          共 2398字,需瀏覽 5分鐘

           ·

          2024-04-12 01:22

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

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

          比如 文件輸入輸出流 等。

          使用try-with-resources關閉資源非常方便,

          示例代碼如下:

          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)遺漏關閉資源的情況。

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

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

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

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

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

          往期推薦

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

          今日代碼 PK | 使用 Optional 判空

          今日代碼 PK | Java 使用正則表達式

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

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

          瀏覽 41
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

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

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  日本人妻精品 | 91成人在线免费视频 | 亚洲操逼视屏 | 精品无码电影 | 在线内射|