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");
}
}
}
|
|