简体   繁体   中英

Closing output stream via StreamResult

I am working on an Android application, and so far so good, however I have a small hiccup which is bothering me.

In the project I'm working with XML files, and I'm saving them to the External Storage of the Android Device. To do this I'm using the TransformerFactory and a StreamResult object.

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer();
DOMSource xmlSource = new DOMSource(xmlDoc);

StreamResult result = new StreamResult(Environment.getExternalStorageDirectory() + "/file.xml");
trans.transform(xmlSource, result);
result.getOutputStream().close();

So, the saving of the file IS working, but the problem I have, is that on the last line, result.getOutputStream().close(); I am getting a Nullpointer Exception.

So my really simple question: Does the stream need to be closed by me, or do some of the methods close it? When I remove the last line, it still saves the file and gives no errors at all, which I am happy with, but I don't want to leave any streams open.

public OutputStream getOutputStream()

Get the byte stream that was set with setOutputStream.

Returns: The byte stream that was set with setOutputStream, or null if setOutputStream or the ByteStream constructor was not called.

As you called the file constructor, the byte stream is not set. As neither the class description nor the file constructor state that you need to close anything manually, it is safe to assume that you don't need to do anything.

EDIT: It depends on the Transformer you are applying, in your case you are using the identity (output=input) transformer. In my setup this is implemented by com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl , which will close any output stream it opens: (lines 760-767)

    // If we create an output stream for the Result, we need to close it after the transformation.
    if (_ostream != null) {
        try {
            _ostream.close();
        }
        catch (IOException e) {}
        _ostream = null;
    }

If you look into the source , you'll see that the class is just a simple bean, it just has 3 fields: systemId , outputStream and writer plus getters and setters.

So basically, the outputStream or writer are available only if someone has set them using setters or the corresponding constructors.

Because you passed the StreamResult into the Transformer , it's not obviously clear what modifications are actually performed on the StreamResult, but I would assume that if you didn't set them yourself, then they would end up being null which is the reason why you get the NPE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM