例如如下读取的文件的io流,我们之前可能会这样写
public class Main {
public static void main(String[] args) {
FileInputStream fileInputStream =null;
try {
fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt")); //打开流
byte[] bytes = new byte[1024];
int line = 0;
//读取数据
while ((line = fileInputStream.read(bytes))!= -1){
System.out.println(new String(bytes,0,line));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileInputStream != null){ //不为空
try {
fileInputStream.close(); //关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}使用try-with-resource写法优雅操作io流
public class Main {
public static void main(String[] args) {
//把打开流的操作都放入try()块里
try( FileInputStream fileInputStream = new FileInputStream(new File("/Users/laoniu/a.txt"))) {
byte[] bytes = new byte[1024];
int line = 0;
while ((line = fileInputStream.read(bytes))!= -1){
System.out.println(new String(bytes,0,line));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}在try()中可以编写多个文件io流或网络io流。让我们看看java编译器是怎么帮我们实现的

可以看到编译后的代码,java编译器自动替我们加上了关闭流的操作。所以跟我们自己关闭流是一样的。try-with-resource这样优雅的写法还是不错的,让代码看起来不那么臃肿。
注意jdk1.7以后才可以用