异常处理:try-with-resources

比try catch要好,不知道为啥,先留个坑。

格式

try (要关闭的资源,是实现了Closeable或者AutoCloseable接口的资源) {

} catch() {

} finally {

}


示例

public static void demo() {
  try (FileInputStream in = new FileInputStream("verb.txt");
       FileOutputStream out = new FileOutputStream("a.txt")) {
      byte[] bytes = new byte[2048];
      int readCount;
      while ((readCount = in.read(bytes)) != -1) {
          out.write(bytes, 0, readCount);
      }
  } catch (FileNotFoundException e) {
      e.printStackTrace();
  } catch (IOException e) {
      e.printStackTrace();
  }
}
posted @ 2021-02-18 22:19  海绵698  阅读(80)  评论(0)    收藏  举报