从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources
语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。
原有拷贝文件代码一般都是在finally
中关闭。
public void copyFile(String fileInput, String fileOutput) {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(fileInput);
output = new FileOutputStream(fileOutput);
byte[] byteArray = new byte[1024];
int len = 0;
while((len = input.read(byteArray)) != -1) {
output.write(byteArray, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用 try-with-resources
语句来简化代码。
public void copyFile(String fileInput, String fileOutput) {
try (InputStream input = new FileInputStream(fileInput);
OutputStream output = new FileOutputStream(fileOutput)) {
byte[] byteArray = new byte[1024];
int len = 0;
while((len = input.read(byteArray)) != -1) {
output.write(byteArray, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
资源会在try
代码后自动关闭,原因就在于它们都实现了AutoCloseable
接口。
Resource
实现AutoCloseable
接口,并拥有open()
方法
public class Resource implements AutoCloseable {
public void open(int value) throws IOException {
if (value == 1) {
throw new IOException();
}
}
@Override
public void close() throws IOException {
System.out.println("Auto close");
}
}
调用open(int)
方法,第一次没有异常发生,正常关闭。第二次发生异常,捕获异常后正常关闭。
public static void main(String[] args) {
try (Resource resource = new Resource()) {
resource.open(0);
} catch (IOException e) {
System.out.println("catch IOException");
}
try (Resource resource = new Resource()) {
resource.open(1);
} catch (IOException e) {
System.out.println("catch IOException");
}
}
输出
Auto close
catch IOException
Auto close