Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 498
superM Avatar asked Dec 25 '12 08:12

superM


2 Answers

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

like image 114
Jon Skeet Avatar answered Oct 06 '22 22:10

Jon Skeet


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.

like image 35
Evgeniy Dorofeev Avatar answered Oct 06 '22 22:10

Evgeniy Dorofeev