如何将 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:47:38  来源:igfitidea点击:

How to convert javax.xml.transform.Source into an InputStream?

javaiotransform

提问by Christopher Klewes

How can I convert a javax.xml.transform.Sourceinto a InputStream? The Implementation of Sourceis javax.xml.transform.dom.DOMSource.

如何将 ajavax.xml.transform.Source转换为 InputStream?的实现Sourcejavax.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 InputStreamor Readerthrough getters. This would be the easiest way.

首先尝试向javax.xml.transform.stream.StreamSource. 如果成功,您可以访问底层InputStreamReader通过 getter。这将是最简单的方法。

If downcasting fails, you can try using a javax.xml.transform.Transformerto transform it into a javax.xml.transform.stream.StreamResultthat 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 StreamSourcecan 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或其他实现