你可以在块中使用多个资源而且这些资源都能被自动地关闭。下面是例子:
private static void printFileJava7() throws IOException {
try( FileInputStream input = new FileInputStream("file.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(input)
) {
int data = bufferedInput.read();
while(data != -1){
System.out.print((char) data);
data = bufferedInput.read();
}
}
}
在java 9中可更为简洁,可以将变量单独放在外边:
private static void printFileJava7() throws IOException {
FileInputStream input = new FileInputStream("file.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(input)
try( input;bufferedInput) {
int data = bufferedInput.read();
while(data != -1){
System.out.print((char) data);
data = bufferedInput.read();
}
}
}
参考资料:
http://ifeve.com/java-7%E4%B8%AD%E7%9A%84try-with-resources/
在 JDK 9 中更简洁使用 try-with-resources 语句