Alexanus
Alexanus

Reputation: 689

Closing Java Input/Output streams

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?

Upvotes: 0

Views: 1606

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61198

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.

Upvotes: 1

Flown
Flown

Reputation: 11750

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.

Upvotes: 1

Related Questions