0

This is my code:

FileOutputStream fos = null;
DataOutputStream dos = null;
try {
    fos = new FileOutputStream(file);
    dos = new DataOutputStream(fos);

    .... writing to file ....

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (dos != null) {
        try {
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I read that you only need to close DataOutpustStream and it will close all other streams, is this correct? Does it do any harm if i close FileOutputStream anyways? What is the best way to close streams?

Alexanus
  • 679
  • 4
  • 22
  • 1
    *"Does it do any harm if i close FileOutputStream anyways?"* - No, but I tend to close streams in the order they were created. try-with-resources is probably the best way to manage these things – MadProgrammer Apr 13 '15 at 07:07
  • Boris answered the *first* question and the *question used to mark this as duplicate* answers the second :) . Closing the `DataInputStream` *implicitly* closes the `FileInputStream` passed to it as an argument. But then again, there are better ways to handle such situations – TheLostMind Apr 13 '15 at 07:10
  • @TheLostMind your duplicate _If you are using Java 7 or later you should consider this question and its answers as obsolete_. Not sure that's the best choice... – Boris the Spider Apr 13 '15 at 07:17

2 Answers2

1

The best way to close streams is when you're using try-resource-blocks. In most cases streams are closed in a cascading manner. For the answer you have to take a closer look into the API.

Flown
  • 11,480
  • 3
  • 45
  • 62
1

No, it doesn't do any harm

You need to close them in the same order that you opened them - think of them as wrappers around each-other. If you create a FileOutputStream and then wrap that in a DataOutputStream, you should close the DataOutputStream first.

But you should use try-with-resources:

try (
        final FileOutputStream fos = new FileOutputStream(file);
        final DataOutputStream dos = new DataOutputStream(fos);
) {
    ....writing to file....

} catch (IOException e) {
    e.printStackTrace();
}

And if you handle the two exceptions in the same way, you can catch the more general IOException only.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • Also note that calling `close()` on a stream which is already closed is *quite harmless* and will not have any *side-effects*. So, if you are unsure about whether the streams passed as arguments to wrappers (DataInputStream) are getting closed or not, call close on them explicitly – TheLostMind Apr 13 '15 at 07:16