java关闭文本_如何更优雅的关闭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 方法。这么写是不是优雅多了??

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/441709.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java类匿名类实例_Java匿名类,匿名内部类实例分析

本文实例讲述了Java匿名类,匿名内部类。分享给大家供大家参考,具体如下:本文内容:内部类匿名类首发日期 :2018-03-25内部类:在一个类中定义另一个类,这样定义的类称为内部类。【包含内部类的类可…

【HDU - 6441】Find Integer (费马大定理 + 奇偶数列法构造勾股定理)

题干: people in USSS love math very much, and there is a famous math problem . give you two integers nn,aa,you are required to find 22 integers bb,cc such that ananbncnbncn. Input one line contains one integer TT;(1≤T≤1000000)(1≤T≤100000…

dart与java互调_Dart与Java不同的地方

数据类型基类是num数值型的操作运算符: 、 - 、* 、/ 、 ~/ 、 %/ 除法 整数余数~/ 除法 取整% 取余常用属性: isNaN、isEven、isOdd (是否非数字、奇偶)常用方法:abs()、round()、floorl()、ceil()、toInt()、toDouble()double nan 0.0 / 0…

算法学习 母函数

母函数又称生成函数。定义是给出序列:a0,a1,a2,.......ak,......,那么函数G(x)a0a1*xa2*x2......ak*xk称为序列a0,a1,a2,.......ak,......的母函数(即生成函数)。 例如:序列1,2,3.......n的生成函数为:G(x)x2x23x3........nxn。点此链接:百度百科 特别…

plsq卸载 删除注册表、_win10操作系统下oracle11g客户端/服务端的下载安装配置卸载总结...

win10操作系统下oracle11g客户端/服务端的下载安装配置卸载总结一:前提注意:现在有两种安装的方式1. oracle11g服务端(64位)oracle客户端(32位)plsql(32位)2. oracle11g服务端(32位)plsql(32位)这里我选择的是第二种 原因是 :首先需要明确ora…

【HDU -1568】 Fibonacci(斐波那契通项公式+取对数)

Fibonacci Problem Description 2007年到来了。经过2006年一年的修炼,数学神童zouyu终于把0到100000000的Fibonacci数列 (f[0]0,f[1]1;f[i] f[i-1]f[i-2](i>2))的值全部给背了下来。 接下来,CodeStar决定要考考他,于是每问他一个数字&a…

java sqlserver分页查询_实现sqlserver分页查询语句

实现sqlserver分页查询语句sqlServer:一次查询,数据库只返回一页的数据。而不是取出所有的数据。pagesize: 每页显示记录数cureentpage:当前页数select * from ( select TOP pagesize * from ( SELECT TOP pagesize*cureentpage…

【HDU - 1269】迷宫城堡 (tarjan算法模板)

题干&#xff1a; 为了训练小希的方向感&#xff0c;Gardon建立了一座大城堡&#xff0c;里面有N个房间(N<10000)和M条通道(M<100000)&#xff0c;每个通道都是单向的&#xff0c;就是说若称某通道连通了A房间和B房间&#xff0c;只说明可以通过这个通道由A房间到达B房间…

php5.4 curl,PHP5.0~5.6 各版本兼容性cURL文件上传功能实例分析

本文实例分析了PHP5.0~5.6 各版本兼容性cURL文件上传功能。分享给大家供大家参考&#xff0c;具体如下&#xff1a;最近做的一个需求&#xff0c;要通过PHP调用cURL&#xff0c;以multipart/form-data格式上传文件。踩坑若干&#xff0c;够一篇文章了。重要警告没事不要读PHP的…

【HDU - 1518】Square (经典的dfs + 剪枝)

题干&#xff1a; Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square? Input The first line of input contains N, the number of test cases. Each test case begins with an integer 4 < M < 20, the number …

php发扑克牌,php 扑克牌代码的简单例子

本文分享下&#xff0c;一段可模拟扑克牌玩法的php代码&#xff0c;有需要的朋友参考下。php 扑克牌代码&#xff0c;如下&#xff1a;cut();* www: jbxue.com*/class cards{/**** Declare our deck variable**/private $deck;/**** Constructor.. duh!**/function __construct…

【HDU - 1026 】Ignatius and the Princess I (bfs + 记录路径)

题干&#xff1a; The Princess has been abducted by the BEelzebub feng5166, our hero Ignatius has to rescue our pretty Princess. Now he gets into feng5166s castle. The castle is a large labyrinth. To make the problem simply, we assume the labyrinth is a N*…

php多线程模拟请求,浅谈php使用curl模拟多线程发送请求

每个PHP文件的执行是单线程的&#xff0c;但是php本身也可以用一些别的技术实现多线程并发比如用php-fpm进程&#xff0c;这里用curl模拟多线程发送请求。php的curl多线程是通过不断调用curl_multi_exec来获取内容&#xff0c;这里举一个demo来模拟一次curl多线程并发操作。//设…

【HDU - 1455】Sticks (dfs + 剪枝)

题干&#xff1a; George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were original…

java找不到符号类socket,编译报错+解决方法:错误: 找不到符号

public class ServerPlainTest { // 包内包外可见public static void main(String[] args) {try {ServerSocket ss new ServerSocket(8189);System.out.println("the server has startuped, waiting for connections.");while (true) { // accept multiple clients …

php hbase thrift,PHP使用Thrift操作Hbase

系统架构图HBase 启动 Thrift服务hbase启动thrift服务// 进入安装的hbase bin目录下// 执行hbase-daemon.sh start thrift2需要注意的是&#xff0c;这里启动的是thrift2服务&#xff0c;如果需要启动thrift服务只需要将thrift2改为thrift就可以了&#xff0c;具体thrift和thri…

【CodeForces - 761D 】Dasha and Very Difficult Problem (构造,思维)

题干&#xff1a; Dasha logged into the system and began to solve problems. One of them is as follows: Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci  bi -…

php excel下载打不开了,php下载excel无法打开的解决方法

php下载excel文件,1、在下载的过程中不要 输出任何非文件信息&#xff0c;比如 echo log信息。 否则下载后的文件无法打开&#xff0c;提示格式错误或者文件被破坏。2、 输出的excel格式一定要和后缀名保存一直&#xff0c;否也会提示格式错误或者文件被破坏if (file_exists(CA…

【CodeForces - 761B】Dasha and friends (思维,模拟,构造)

题干&#xff1a; Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length L, in distinct points of which there…

php字符串变量,PHP 字符串变量

PHP 字符串变量字符串变量用于存储并处理文本。PHP 中的字符串变量字符串变量用于包含有字符的值。在创建字符串之后&#xff0c;我们就可以对它进行操作了。您可以直接在函数中使用字符串&#xff0c;或者把它存储在变量中。在下面的实例中&#xff0c;我们创建一个名为 txt 的…