从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。
带资源的try catch
1.自动释放资源格式:
try(
资源
){
}catch{
}
2.最初关闭资源方式
private static void customBufferStreamCopy(File source, File tar) {
InputStream fis = null;
OutputStream fos = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(tar);
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);
}
}
3.现在使用关闭方式.,则不需要在finally中进行数据关闭。将资源关闭不需要写代码操作
private static void customBufferStreamCopy(File source, File tar) {
InputStream fis = null;
OutputStream fos = null;
try (
fis = new FileInputStream(source),
fos = new FileOutputStream(tar)
){
byte[] buf = new byte[8192];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
4.前提是资源必须:这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。
例如:以下这些类或者子接口都支持此方法,因为他们都实现了 java.lang.AutoCloseable
5.例如我们可查看:
我们将FIleInputStream 放置try()中
点进去看FIleInputStream.发现继承至InputStream
点进去看InputStream.发现实现了Closeable
点进去看Closeable.发现实现了AutoCloseable
发现Closeable 继承至AutoCloseable .那么即满足了带资源关闭的基本要求。当try 中的{ } 执行完后,将会自动关闭资源