问题描述
我的应用需要执行以下操作:
My app needs to do the following:
- 打开
FileInputStream
,并获取基础FileDescriptor
(通过getFd()
) - 创建新的
FileInputStream
基于以上FileDescriptor的对象
- Open a
FileInputStream
, and obtain the underlyingFileDescriptor
(viagetFd()
) - Create new
FileInputStream
objects based on the aboveFileDescriptor
到目前为止,我只需要一个 FileDescriptor
,所以我以前通过调用 close()$ c $关闭它c>在原始流上(即在我调用的
getFd()
的流上)。我使用它是因为一些Android API方法有这样的参数。
So far, I only needed one FileDescriptor
, so I used to close it by calling close()
on the original stream (i.e. on the stream which getFd()
I called). I use it because some Android API methods have such a parameter.
现在我将有更多的 FileInputStream
对象同时,何时关闭 FileDescriptor
? (我猜:当所有 FileInputStream
对象都关闭?)
Now that I will have more FileInputStream
objects at the same time, when will the FileDescriptor
be closed? (My guess: when all FileInputStream
objects are closed?)
推荐答案
我相信你是对的。一个小测试显示 FileDescriptor
在 FileInputStream
关闭后变为无效。请注意,对于相同 FileDescriptor
的多个 FileInputStream
, FileDescriptor
一旦第一个 FileInputStream
关闭就变为无效,即如果你先关闭 fis1 $ c无关紧要$ c>然后
fis2
或者相反:
I belive you are right. A small test shows that the FileDescriptor
becomes invalid after its FileInputStream
is closed. Note that, in case of more than one FileInputStream
for the same FileDescriptor
, the FileDescriptor
becomes invalid as soon as its first FileInputStream
is closed, i.e. it does not matter if you close first fis1
and then fis2
or the other way around:
FileInputStream fis1 = new FileInputStream("/tmp/adb.log");
FileDescriptor fd = fis1.getFD();
FileInputStream fis2 = new FileInputStream(fd);
System.out.println(fd.valid());
fis1.close();
System.out.println(fd.valid());
fis2.close();
System.out.println(fd.valid());
输出为:
true
false
false
别忘了在 finally
块中关闭流,以确保在I / O(读/写)错误的情况下也关闭它。
Do not forget to close the stream in a finally
block, to make sure you close it also in case of an I/O (read/write) error.
这篇关于FileDescriptor什么时候关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!