java的try后⾯跟括号
如题,在⼯作中遇见了在atch语句的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;
try catch的使用方法
int temp=0;          //所有读取的内容都使⽤temp接收
while((ad())!=-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((ad())!=-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 接⼝。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。