Closing StreamSource

浪尽此生 提交于 2019-12-13 03:49:02

问题


I was getting a too many open files error on my web service and just wanted to make sure that there's nothing else that I have to close. I added a close() on outWriter (StringWriter), but the JavaDoc said that this has no effect. getCachedExtractSoapBodyXslt() gets the javax.xml.transform.Transformer object.

String payload;
StreamResult result=null;
StringWriter outWriter=null;
try {
    // Programmatically extract the SOAP Body from message
    outWriter = new StringWriter();
    result = new StreamResult(outWriter);
    Source src = new StreamSource(new java.io.StringReader(doc));
    getCachedExtractSoapBodyXslt().transform(src, result);
    StringBuffer sb = outWriter.getBuffer();
    payload = sb.toString();
} catch (TransformerException e) {
    throw new ComponentException("Unable to extract SOAP Body");
}
finally {
    LOG.debug("Closing XSLT transformer output stream");
    try {
        outWriter.close();
    }
    catch (IOException e) {
        LOG.error("Failed to close stream for SOAP message");
    }
}

回答1:


I had to move this to it's own variable and to close it

new java.io.StringReader(doc)



回答2:


StreamSource has no close, and what I've observed the users of it don't close the stream or reader it holds. And try-with-resource isn't an option either since it's not "closeable". So had to go old school and use a try/finally that called it's getInputStream and GetReader methods and pass their result to IOUtils.closeQuietly

StreamSource source = null;
try {
   source = new StreamSource(inputStream);
   // Do stuff with source
}
finally {
   IOUtils.closeQuietly(source.getInputStream());
}

In my case I actually had to call both getInputStream and getReader since my source was constructed in two different ways.



来源:https://stackoverflow.com/questions/24456836/closing-streamsource

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!