栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

如何更优雅的关闭java文本、网络等资源

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何更优雅的关闭java文本、网络等资源

通常在 java 中对文本、网络资源等操作起来是很繁杂的,要声明,读取,关闭三个阶段,还得考虑异常情况。假设我们要读取一段文本显示到控制台,通常会有如下的代码:

public static void main(String[] args) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream("./pom.xml");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
String str;
while ((str = reader.readLine()) != null) {
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
}
}
}

在 finally 的关闭代码中,还要再来一个 try/catch,看着是不是很难受,很不优雅,很想干掉这个 finally!

自从 java7 以来这个问题已经有比较好的解决办法了,那就是try-with-resource,可能是 jdk 开发人员也觉得之前的关闭资源写法太反人类,所以做了这样的一个语法糖。注意这并不是什么新特性,只是一个语法糖,简化代码的。如果你反编译代码后会发现还是 try/catch/finally 的传统写法。

try-with-resource 用法如下:

try (FileInputStream inputStream = new FileInputStream("./pom.xml")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String str;
while ((str = reader.readLine()) != null) {
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}

无需在 finally 中手动关闭 inputStream,凡是实现了 AutoCloseable 接口的,且在 try 后面的括号中创建的,都会在 try/catch 执行完毕后确保调用 close 方法。这么写是不是优雅多了??

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/137907.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号