Java如何使用try-with-resources语句?
该try-with-resources语句在Java7中引入。使用此新语句,我们可以简化程序中的资源管理,该程序也称为ARM(自动资源管理)。
此语句是try声明一个或多个资源的语句。程序使用完资源后,必须将其关闭。在try-with-resources确保每个资源被关闭,语句的结束。
任何实现的对象(java.lang.AutoCloseable包括所有实现的对象)java.io.Closeable都可以用作资源。
package org.nhooo.example.basic;
import java.io.*;
public class TryWithResourceExample {
public static void main(String[] args) {
try {
TryWithResourceExample demo = new TryWithResourceExample();
demo.printStream("/tmp/data.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
private void printStream(String fileName) throws IOException {
char[] buffer = new char[1024];
try (InputStream is = new FileInputStream(fileName);
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"))) {
while (reader.read(buffer) != -1) {
System.out.println(buffer);
}
}
}
}