是否需要在android中关闭参数/参数InputStream? [英] Does argument/parameters InputStream need to be closed in android?

查看:70
本文介绍了是否需要在android中关闭参数/参数InputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有流和bufferedReader都需要关闭,我的问题是 流和bufferedReader在方法参数/参数内部 还需要关闭吗?

All stream and bufferedReader need to be closed my question is what if the stream and bufferedReader is inside a method arguments/parameters need to be closed also?

正常代码示例:

InputStream i = entity.getContent();
i.close();

Q:如果它的内部仅传递了一个方法的参数,那该怎么办

Q: What if its inside an arguments of a method that has been pass only

public void doDownload(InputStream i, BufferedReader b) {
    i.close();
    b.close();
}

即使inputstream和bufferedreader只是一个参数,我也应该关闭它吗? 并没有对象?

should i also close it even that inputstream and bufferedreader is only an arguments and don't have an Object?

推荐答案

只要(某人)将其关闭,这(主要)是样式问题.但是,一致的方法效果最好.管理此类资源的关键技术是明确其所有权:资源的所有者负责释放它.这种所有权可以在资源的生命周期内更改,但是在任何时候都应该清楚.

This is (mostly) a matter of style, as long as someone closes them. However, a consistent approach works best. The key technique to manage this kind of resources is to make their ownership clear: the owner of the resource is responsible for releasing it. This ownership can change during the lifetime of the resource, but it should be clear at any point.

在这种情况下:

public void doDownload(InputStream i, BufferedReader b) { ... }

该流和阅读器不是通过此方法创建的,而是提供给它的.因此,应由调用方来负责关闭它.此方法执行完后,它甚至可能继续使用资源,因此不应将其关闭.

the stream and reader was not created by this method, but was rather provided to it. Therefore, it is the caller who should be responsible for closing it. It may even continue using the resource after this method finishes executing, so it should not be closed.

但是,在某些情况下,调用方法可能是转移资源所有权的一种形式.一个明显的例子是Java中的流链-通过包装另一个OutputStream创建一个OuputStream意味着外部的一个现在负责关闭内部的一个.

However, in some cases, calling a method may be a form of transferring ownership of the resource. A clear example of this is stream chaining in Java -- creating an OuputStream by wrapping another OutputStream means the outer one is now responsible for closing the inner one when it's closed itself.

在另一个示例中:

InputStream i = entity.getContent();

这取决于细微的差异. getContent()方法实际上是 create InputStream创建的,还是只是获得对实际上属于entity对象的资源的引用?在第一种情况下,则调用方方法应负责释放它.否则,实体类应自行执行(按照 RAII 模式).

it depends on a subtle difference. Did the getContent() method actually create the InputStream, or just obtain a reference to a resource that actually belongs to the entity object? In the first case, then the caller method should be responsible for releasing it. Otherwise, the Entity class should do itself (as per the RAII pattern).

一个更清晰的例子是:

InputStream i = context.openFileInput(fileName);

在这种情况下,调用方显然负责创建InputStream,因此负责关闭它.

In this case, the caller is clearly responsible for the creation of the InputStream, and therefore is responsible for closing it.

这篇关于是否需要在android中关闭参数/参数InputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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