Java关闭流的方式

情景

写代码时发现如果打开了多个stream,那么关闭的时候需要些很多冗余代码。就像下面这样:

public static void main(String[] args) {
	File file = new File("D:" + File.separator + "test.txt");
	InputStream in = null;
	try {
		in = new FileInputStream(file);
		// operation input stream
		// ...
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
                // !!!这里如果要关闭的流很多,那么就会写出很多冗余且相似的代码
		if (in != null) {
			try {
				in.close();
			} catch (IOException e) {
				// ignore
			}
		}
	}
}

如果打开的流超过10个,那么代码中很多都是上面那样的代码。所以,需要编写方法去统一处理关闭流。

解决

方法1:自行编码实现

可以把这个方法放到工具类中。但是本着不要重复造轮子的想法, 应该有工具类已经实现了这个方法。


private void close(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

方法2:使用commons-io的IOUtils

Maven坐标:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

源代码:


    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

调用示例:

public static void main(String[] args) {
	File file = new File("D:" + File.separator + "test.txt");
	InputStream in = null;
	try {
		in = new FileInputStream(file);
		// operation input stream
		// ...
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		IOUtils.closeQuietly(in);
	}
 
}

方法3:try-with-resource (JDK1.7+)

在common-io-2.6版本中,这个IOUtils.closeQuietly(arg0);方法已经被弃用了,并且没有替代方案。

@Deprecated的说明如下:As of 2.6 removed without replacement. Please use the try-with-resources statement or handle suppressed exceptions manually.给我们的建议就是使用try-with-resources语句或者手动处理压制的异常。

try-with-resource这个语法糖是JDK1.7开始引入的,具体语法如下:

/**
 * auto closeable stream为实现自动关闭的Stream
 * JDK1.7 新增了一个java.lang.AutoCloseable接口,接口内部只有close()方法。
 * JDK1.7 同时修改了java.io.Closeable接口,这个接口继承了AutoCloseable接口。
 * 所以之前那些实现Closeable接口的stream都可以实现AutoCloseable接口中的自动关闭的功能。
 */
try (auto closeable stream) {
    
} catch (Exception e) {
}

示例:

public static void main(String[] args) {
	File file = new File("D:" + File.separator + "test.txt");
	try (InputStream in = new FileInputStream(file)) {
		// operation input stream
		// ...
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// ignore
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
前 言 1 1 概 述 2 1.1 选题背景 2 1.2 组织结构 2 2 所用相关技术和方法 3 2.1 工作 3 2.1.1 什么叫工作 3 2.1.2 工作发展 3 2.1.3 工作的优点 3 2.2 MVC工作模式 4 2.2.1 MVC设计思想 4 2.2.2 MVC的具体实现 5 2.2.3 MVC的不足 6 2.3 JSP技术介绍 6 2.3.1 JSP的运行原理 7 2.3.2 JSP的生命周期 8 2.3.3 Servlet和JavaBean技术介绍 8 2.3.4 Java 虚拟机 9 2.3.5 JSP访问SQL Server 2000数据库 9 2.4 数据库后台环境配置 10 2.5 系统开发工具简介 10 2.5.1 Dr eamweaver 10 2.5.2 MyEclipse 10 2.5.3 Tomcat 11 2.5.4 SQL Server2000 11 2.5.5 chs_sql2ksp3 12 3 系统需求分析 13 3.1 系统功能分析 13 3.2 系统性能分析 13 3.3 系统方案的确定和评价 13 4 系统总体设计 15 4.1 系统层次模块图 15 4.1.1 营业厅模块 15 4.1.2 收费管理模块 16 4.2 系统数据程图 16 4.3 数据表设计 18 5 详细设计及编码 21 5.1 编写JAVABEAN 21 5.2 营业厅实现函数 21 5.3 收费厅主要的实现函数 22 5.4 JAVABEAN主要实现模块 22 5.4.1 中文字符格式的转换模块(Stringto.java) 22 5.4.2 自动生成验证码(Ran.java) 22 5.4.3 数据库的连接(ConnectionFactory.java) 23 5.4.4 数据库连接的关闭(DatabaseUtils.java)--只提供接口 23 5.4.5 密码修改模块(Common_fuction.java) 24 5.4.6 时间格式转换(timeBean.java) 24 5.4.7 数据统计(counthander.java) 25 5.4.8 营业厅的接口(luruaction.java) 27 5.4.9 营业厅的主要函数实现(luruhander.java) 28 5.4.10 收费厅的主要函数接口 32 5.5 管理员登陆模块 33 5.5.1 管理员登录 33 5.6 营业厅管理模块 36 5.6.1 Left.jsp页面 36 5.6.2 Work.jsp 40 5.6.3 customerlistinfo.jsp 41 5.6.4 allinfo.jsp 41 5.7 收费厅管理模块 42 5.7.1 Left.jsp 42 5.7.2 Work.jsp 43 5.7.3 Customerlistinfo.jsp 43 5.7.4 gongdan.jsp 43 6 系统测试与维护 45 6.1 测试目的 45 6.2 测试环境 45 6.3 系统测试 45 6.4 系统维护 45 7 开发难点与技术 46 7.1 主要程序实现的代码描述 46 7.1.1 验证码的自动生成 46 7.1.2 生成WORD工单 46 7.1.3 以一定的时间刷新页面 47 7.1.4 JSP中文问题的解决 47 7.2 在程序编码过程遇到的主要问题: 48 7.3 代码编写风格 49 7.4 我的不足: 49 结束语 50 致 谢 50
Java 中,当使用 I/O 读取或写入数据时,必须正确关闭以释放系统资源。关闭的最佳方法是使用 try-with-resources 语句,它会自动关闭,以便在代码块结束时释放资源。 以下是使用 try-with-resources 语句正确关闭 I/O 的示例代码: ``` try (FileInputStream fis = new FileInputStream("file.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } ``` 在这个示例中,我们使用 try-with-resources 语句打开一个文件输入、一个输入读取器和一个缓冲读取器。当代码块结束时,这些将自动关闭,无需显式调用 `close()` 方法。 如果你使用的是旧版本的 Java,没有 try-with-resources 语句,你可以在 finally 块中显式关闭。以下是使用 finally 块关闭的示例代码: ``` FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; try { fis = new FileInputStream("file.txt"); isr = new InputStreamReader(fis); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (isr != null) { isr.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } ``` 在这个示例中,我们在 try 块中打开,并在 finally 块中关闭它们。在 finally 块中,我们检查每个是否为 null,然后调用其 `close()` 方法关闭它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值