
自动调用close()方法 |
原来: |
FileInputStream in = null; |
FileOutputStream out = null; |
try { |
in = new FileInputStream("xanadu.txt"); |
out = new FileOutputStream("outagain.txt"); |
int c; |
while ((c = in.read()) != -1) |
out.write(c); |
} finally { |
if (in != null) |
in.close(); |
if (out != null) |
out.close(); |
} |
现在: |
try ( //注意,这里是 ( 不是{ |
FileInputStream in = new FileInputStream("xanadu.txt"); |
FileOutputStream out = new FileOutputStream("outagain.txt") |
) { |
int c; |
while((c=in.read()) != -1 ) |
out.write(); |
} |
1.在资源部分中,最后一个资源后面是不允许使用分号的。 |
2.资源块使用()分隔,而不是常见的{},以此将其与现有的try块分隔开来。如果存在资源块,那么里面必须要包含一个或多个资源定义语句。 |
3.每个资源定义具有如下形式:type var = expression;在资源块中不能使用通常的语句 |
4.资源都是隐式final的,也就是说即便没有使用final,这些资源也都是final的。如果尝试为资源变量赋值会得到一个编译期错误。 |
5.资源必须是AutoCloseable的子类型,如果不是的话会得到一个编译期错误。 |
6.资源关闭的顺序与定义的顺序正好相反。 |




by: 发表于:2017-07-17 16:46:22 顶(0) | 踩(0) 回复
??
回复评论