superM
superM

Reputation: 8695

Do I need to close Input Stream manually?

I'm using Xerces library for parsing XML. Here is the code snippet for parsing:

Document doc = builder.parse(new InputSource(new StringReader(someXMLString)));

Do I need to close the InputStream in InputSource manually or will the parse method handle it?

Upvotes: 6

Views: 3341

Answers (6)

Andremoniy
Andremoniy

Reputation: 34900

InputSource is just a convenient class-wrapper on the stream, so it doesn't close the stream within it.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

It seems there is nothing in DocumentBuilder API about it. We can test it as

InputStream is = new FileInputStream("test.xml") {
    @Override
    public void close() throws IOException {
        System.out.println("close");
        super.close();
    }
};
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
documentBuilder.parse(is);

it prints close. But since there's nothing in API about it, this behaviour is not guaranteed.

Upvotes: 2

Qiang Jin
Qiang Jin

Reputation: 4467

You should close it by yourself.

The builder.parse method doesn't close the stream in its implementation. It won't know when is suitable to close the stream, so this requires the stream being manually closed.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502396

Given that you've got no external resources - just a StringReader - you don't need to close it. I would do so anyway though... then if you ever change the code to use a different input, you won't accidentally have a resource leak.

(For just throwaway code, I'd leave it - but be aware that if you're not careful, throwaway code has a habit of living longer than expected.)

Upvotes: 6

Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23972

InputStream supposed to be closed, since close() method:

Closes this input stream and releases any system resources associated with the stream.

It's doesn't matter is your stream uses resources or not - it's good way to close it. Just to be sure.

Upvotes: 0

RNJ
RNJ

Reputation: 15552

If you use try-with then you can let java close it for you. Otherwise I would recommend closing it manually.

Upvotes: 0

Related Questions