在Java中关闭输入流 [英] Closing inputstreams in Java

查看:283
本文介绍了在Java中关闭输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在try / catch块中有以下代码

I have the following piece of code in a try/catch block

 InputStream inputstream = conn.getInputStream();
 InputStreamReader inputstreamreader = new  InputStreamReader(inputstream);
 BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

我的问题是,当我必须在finally块中关闭这些流时,我是否必须关闭所有3个流或只是关闭 befferedreader 将关闭所有其他流?

My question is that when I have to close these streams in the finally block, do I have to close all the 3 streams or just closing the befferedreader will close all the other streams ?

推荐答案

按惯例,包装器流(包装现有的流)在关闭时关闭底层流,因此只需在示例中关闭 bufferedreader 。此外,关闭已经关闭的流通常是无害的,因此关闭所有3个流不会受到伤害。

By convention, wrapper streams (which wrap existing streams) close the underlying stream when they are closed, so only have to close bufferedreader in your example. Also, it is usually harmless to close an already closed stream, so closing all 3 streams won't hurt.

这篇关于在Java中关闭输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆