How to convert javax.xml.transform.Source into an InputStream?
How can I convert a javax.xml.transform.Source
into a InputStream? The Implementation of Source
is javax.xml.transform.dom.DOMSource
.
Source inputSource = 开发者_StackOverflow社区messageContext.getRequest().getPayloadSource();
First try to downcast to javax.xml.transform.stream.StreamSource
. If that succeeds you have access to the underlying InputStream
or Reader
through getters. This would be the easiest way.
If downcasting fails, you can try using a javax.xml.transform.Transformer
to transform it into a javax.xml.transform.stream.StreamResult
that has been setup with a java.io.ByteArrayOutputStream
. Then you return a java.io.ByteArrayInputStream
. Something like:
Transformer t = // getTransformer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); t.transform(inputSource, result); return new ByteArrayInputStream(os.getByteArray());
Of course, if the StreamSource
can be a large document, this is not advisable. In that case, you could use a temporary file and java.io.FileOutputStream
/java.io.FileInputStram
. Another option would be to spawn a transformer thread and communicate through java.io.PipedOutputStream
/java.io.PipedInputStream
, but this is more complex:
PipedInputStream is = new PipedInputStream(); PipedOutputStream os = new PipedOutputStream(is); Result result = new StreamResult(os); // This creates and starts a thread that creates a transformer // and applies it to the method parameters. spawnTransformerThread(inputSource, result); return is;
It's not normally possible, unless it can be down-casted to StreamSource or other implementations.
精彩评论