欢迎光临散文网 会员登陆 & 注册

java try-with-resource自动关闭

2022-07-09 21:19 作者:虚云幻仙  | 我要投稿

/**
* try-with-resource自动关闭
*/

public class Test04 {
   public static void main(String[] args) {
       try(FileReader reader = new FileReader("C:/a.txt");){
           //将打开文件的操作包在try()中 实现try/catch执行完成后自动关闭文件
           System.out.println((char) reader.read());
           //{}语句块中照常对reader操作
       }catch (Exception e){
           e.printStackTrace();
       }
       //不需要finally{.close()}

       try (
               FileReader reader1 = new FileReader("C:/a");
               FileReader reader2 = new FileReader("C:/b")
           ){
           //可以同时打开多项
       }catch (Exception e){
           e.printStackTrace();
       }

       //try-with-resource在经过编译后会还原成try/catch/finally给虚拟机运行
   }
}

java try-with-resource自动关闭的评论 (共 条)

分享到微博请遵守国家法律