A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 王红潮 中级黑马   /  2012-9-12 14:25  /  1884 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

7.0以前如果需要关闭资源,必须写在在finally语句块中,7.0只要资源实现了AutoCloseable 或者Closeable接口,实现了close方法就可以应用自动关闭资源的try语句了,简化书写
例如:
FileInputStream fis = null;
try
{
  fis = new FileInputStream("a.txt");
}
finally
{
   if(fis!=null)
   {
     fis.close(); //还要try...catch
    }
}

现在可以这样写了:
public class AutoCloseTest {
public static void main(String[] args) throws IOException {
  try(
       //把资源括起来,让系统自动关闭资源
   BufferedReader br = new BufferedReader(new FileReader("autottest.java"));
   PrintStream ps = new PrintStream(new FileOutputStream("a.txt"))
     ){
   System.out.println(br.readLine());
   ps.println("test document");
   
  }
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马