Io流关闭问题

24 篇文章 0 订阅

错误案例

常见的一种写法,针对每个catch都进行一次io流关闭。在关闭过程也未进行io流的空值判断。

    try{
	URL url = new URL("http://pm.china.alibaba.com/" + memberId);
	URLConnection conn = url.openConnection();
	reader.close();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
	try {
		reader.close();
	} catch (IOException e1) {
	}
    }

错误分析

使用catch异常的方式关闭io流,需要注意catch的分支必须得写全,而且需要针对空值,流关闭异常进行处理,导致代码不是很优雅。 也很容易造成io流没有正常关闭,出现open too many files的情况。

正确用法

1. 在finnally 中关闭io流,避免catch分支的遗漏 2. 使用一些utils关闭io流

    try{
	URL url = new URL("http://pm.china.alibaba.com/);
	URLConnection conn = url.openConnection();
    } catch (Exception e) {
	// do log xxxx
    } finally {
	Ioutils.closeQuietly(reader)
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 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()` 方法关闭它们。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值