如题,在工作中遇见了在try...catch语句的try后面加括号,不懂,查资料明白之后,特此记录.
下面是一段很简单的从文件读取文本的输入流:
package com.springcloud.server.springserver;
import java.io.*;
public class TryTest {
public static void main(String[] args) {
File file = new File("E:\\springcloud\\spring-eureka\\src\\main\\resources\\a.txt");
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte b[] = new byte[1024];
int len = 0;
int temp=0; //所有读取的内容都使用temp接收
while((temp=inputStream.read())!=-1){ //当没有读取完时,继续读取
b[len]=(byte)temp;
len++;
}
System.out.println(new String(b,0,len));
}catch (Exception e){
e.printStackTrace();
}finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
有一定java功底的人一眼就看的明白,非常简单.
但是,在java1.7的版本中,我们还有另外一种写法来关闭这个inputstream,也就是在try后面加括号,代码如下:
package com.springcloud.server.springserver;
import java.io.*;
public class TryTest {
public static void main(String[] args) {
File file = new File("E:\\springcloud\\spring-eureka\\src\\main\\resources\\a.txt");
try (InputStream inputStream = new FileInputStream(file)){
byte b[] = new byte[1024];
int len = 0;
int temp=0; //所有读取的内容都使用temp接收
while((temp=inputStream.read())!=-1){ //当没有读取完时,继续读取
b[len]=(byte)temp;
len++;
}
System.out.println(new String(b,0,len));
}catch (Exception e){
e.printStackTrace();
}
}
}
为了验证,我们在FileInputStream的close方法处打上断点,并且以debug的方式启动上面的方法:
启动,发现我们没有显示的写close(),程序还是进入了close()方法:
由此可知,在try后面写的内容是可以自动帮我进行close()的.
总结:
从java1.7版本开始,支持使用try后面跟随()括号管理释放资源,前提是这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。