所谓try-with-resources语句就是在try后面加上resources,跟平常见到的try-catch语句有差别。
先看个例子:
File srcFile = new File(srcPath);
File dstFile = new File(dstPath);
try (FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(dstFile)){
byte[] bytes = new byte[1024];
int count = fis.read(bytes);
if(count != -1) {
fos.write(bytes);
}
} catch (Exception e) {
e.printStackTrace();
}
其中try后面圆括号内的东西即为resources,resources必须为实现java.lang.AutoCloseable或者java.io.Closeable接口的类
,使用后可以自动close以释放资源,并且resources可以有多个,用分号间隔开。try-catch语句执行完resources即自动释放掉,不需要自己再去close,我们可以简单验证下。
//定义一个自己的Closeable类
class MyCloseable implements Closeable{
@Override
public void close() throws IOException {
Log.v("test", "---close---");
}
}
//try-with-resources语句
Log.v("test", "---111---");
try (MyCloseable myCloseable = new MyCloseable()) {
Log.v("test", "---222---");
} catch (Exception e) {
e.printStackTrace();
}
Log.v("test", "---333---");
//打印结果
V/test: ---111---
V/test: ---222---
V/test: ---close---
V/test: ---333---
使用这种语句可以避免没有释放资源导致内存泄露之类的问题。
需要注意的是,try-with-resources语句在Android SDK大于等于19才可以使用。