如何将 javax.xml.transform.Source 转换为 InputStream?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3711239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert javax.xml.transform.Source into an InputStream?
提问by Christopher Klewes
How can I convert a javax.xml.transform.Source
into a InputStream? The Implementation of Source
is javax.xml.transform.dom.DOMSource
.
如何将 ajavax.xml.transform.Source
转换为 InputStream?的实现Source
是javax.xml.transform.dom.DOMSource
。
Source inputSource = messageContext.getRequest().getPayloadSource();
采纳答案by gpeche
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.
首先尝试向javax.xml.transform.stream.StreamSource
. 如果成功,您可以访问底层InputStream
或Reader
通过 getter。这将是最简单的方法。
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:
如果向下转换失败,您可以尝试使用 ajavax.xml.transform.Transformer
将其转换为javax.xml.transform.stream.StreamResult
已使用java.io.ByteArrayOutputStream
. 然后你返回一个java.io.ByteArrayInputStream
. 就像是:
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:
当然,如果StreamSource
可以是大文件,这是不可取的。在这种情况下,您可以使用临时文件和java.io.FileOutputStream
/ java.io.FileInputStram
。另一种选择是产生一个转换器线程并通过java.io.PipedOutputStream
/ 进行通信java.io.PipedInputStream
,但这更复杂:
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;
回答by Mohsen
It's not normally possible, unless it can be down-casted to StreamSourceor other implementations.
这通常是不可能的,除非它可以向下转换为StreamSource或其他实现。