Jdk1.7(及以上) 使用 try-with-resources 替代try-catch-finally

Java 1.7及更高版本引入了try-with-resources语句,它允许自动关闭实现了AutoCloseable或Closeable接口的资源。这种方式在结束try代码块时会自动调用资源的关闭方法,简化了对流和读取器等资源的管理。例如,常见的Stream和Reader都支持此特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚刚在看 Jedis's Wiki 的时候,发现里边的代码,用了一句

还没见过这样的语法,于是乎到官方找了一下解释  http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

只要你的对象实现了AutoCloseable 或 Closeable,在try代码块结束之前,会自动关闭资源.

我还用 Idea 找了一下 AutoCloseable 的实现类,常用的 Stream,Reader 都实现了.

所以常用的这些Stream和Reader都可以放心使用try-with-resources.

例子:

static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}


 public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
    throws java.io.IOException {


    java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");
    java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);


    // Open zip file and create output file with try-with-resources statement


    try (
      java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
      java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {


      // Enumerate each entry


      for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {


        // Get the entry name and write it to the output file


        String newLine = System.getProperty("line.separator");
        String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
        writer.write(zipEntryName, 0, zipEntryName.length());
      }
    }
  }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值