Search code examples
javaandroidfile-descriptorfileinputstream

When is FileDescriptor closed?


My app needs to do the following:

  • Open a FileInputStream, and obtain the underlying FileDescriptor (via getFd())
  • Create new FileInputStream objects based on the above FileDescriptor

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.

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?)


Solution

  • 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());
    

    Output is:

    true
    false
    false
    

    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.