引言
在程序开发过程中,存在着这样的应用场景:需要读取文件,读取结束之后需要关闭资源;
比如下面的开发场景:
读取了 test.txt 文件,读取结束之后,需要关闭资源,不关闭的话,会造成系统资源的浪费;
public static void main(String[] args) {
//读取文本文件的内容
Scanner scanner = null;
try {
scanner = new Scanner(new File("/test.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
}
上面的开发方式存在的问题
每次打开一个资源,后面必须关闭一个资源,关闭资源的方式比较麻烦;
如果一个方法中打开了很多的资源之后,开发者可能忘记关闭某个资源;
问题的解决
使用 try - with - resource 可以解决这个问题
public static void tryResource() {
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
\
与上面代码块的不同之处在于 try - with - resource 将文件的打开放置到了 try 后面的小括号中;
这样一来,开发者只是需要写 try - catch 语句,不需要在 finally 中释放资源了;
这样做一方面减少了开发者的工作,一方面提升了程序运行的效率;
多个文件的同时打开与关闭
当需要放个文件资源打开的时候,在 try 后面的小括号中使用 ‘;’ 分开即可,如下所示:
public static void tryResourceMulti() {
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
try catch finally 和 try with resource 语法结构差异
try catch finally:
try{
} catch {
} finally {
}
try with resource:
try (书写读取资源的代码,读取结束后自动释放资源) {
} catch {
}
小结
本文比较了 try - catch - finally 与 try - with resource 之间的区别,在开发中,十分推荐使用 try - with - resource 的方法进行资源的打开,因为这样做程序会自动的释放资源,减少开发者的压力。