您的位置:首页 > 编程语言 > Java开发

java try后面括号的作用

2017-11-29 17:50 281 查看
Java7新特性,支持使用try后面跟随()括号管理释放资源

例如通常使用try代码块

try {
fis = new FileInputStream(source);
fos = new FileOutputStream(target);

byte[] buf = new byte[8192];

int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
close(fis);
close(fos);
}

使用Java7新特性

try (
InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target)){

byte[] buf = new byte[8192];

int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
}try括号内的资源会在try语句结束后自动释放,前提是这些可关闭的资源必须实现
java.lang.AutoCloseable 接口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 7 try 括号