java中的错误流_关于java中流关闭的问题
发布日期:2021-06-24 13:10:20 浏览次数:2 分类:技术文章

本文共 1542 字,大约阅读时间需要 5 分钟。

有如下代码:

private static String extractContent(HttpResponse response) throws Exception {

String htmStr = null;

if (response.getStatusLine().getStatusCode() == 200) {

if (response != null) {

BufferedReader br = null;

InputStream ins = null;

代码中的br 和ins都正确的关闭掉了。但是在使用InputStreamReader的时候,是通过

br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));

来使用的,那么InputStreamReader是否需要显示的关闭,即改成:

private static String extractContent(HttpResponse response) throws Exception {

String htmStr = null;

if (response.getStatusLine().getStatusCode() == 200) {

if (response != null) {

BufferedReader br = null;

InputStream ins = null;

InputStreamReader inr = null;

try {

HttpEntity entity = response.getEntity();

ins = entity.getContent();

inr = new InputStreamReader(ins, "UTF-8");

br = new BufferedReader(inr);

StringBuffer sbf = new StringBuffer();

String line = null;

while ((line = br.readLine()) != null) {

sbf.append(line);

}

我知道在JDK7之后提供了try with resources的方法解决了这种问题,但是在JDK7之前是不是必须的这样用,显示的分别new相应流对象,然后最后再关闭,而不能

br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));

像这样嵌套这来用。

我的问题:

1.如果没有流关闭,会带来安全隐患,具体带来何种安全隐患?最好能举例说明。还有说没有正确的关闭流,会造成系统资源的浪费,具体是指什么?(我的理解是浪费CPU资源,导致CPU轮询去查询是否有I/O传输,这样的理解对不对啊)??

2.jdk1.7之前,流的使用,是不是必须要用这种结构:

BufferedReader ins = null;

InputStreamReader inr = null;

try{

ins = ...

inr = ...

}catch{

...

}finally{

if(null != ins) ins.close;

if(null != inr) inr.close;

}

而不能使用这样的结构:

BufferedReader ins = null;

try{

ins = new InputStreamReader(new InputStrea(System.in, "UTF-8"));

}catch{

...

}finally{

if(null != ins) ins.close;

}

转载地址:https://blog.csdn.net/weixin_33001305/article/details/114565908 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java课题研究方法和技术途径_课题研究的基本方法有哪些?
下一篇:java list keystore_Java / Keystore验证签名证书

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年03月30日 23时10分49秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章