使用标准Java库获取Writer的InputStream
我有一个将数据写入 OutputStream 的方法,但需要将 OutputStream 的内容作为输入流返回。
public InputStream getInputStreamOfData(type param) {
// ..... data
OutputStreamWriter writer = new OutputStreamWriter();
writer.write(data);
// convert writer object to an InputStream
}
我遇到了一些库来执行此操作,例如 IOUtils 和其他基于线程的方法。有没有一种简单的方法可以使用标准 Java 库来实现这一点?我想将编写器中的内容作为 InputStream 返回以供调用方法使用。
谢谢!
I have an method which writes data to an OutputStream but needs to return the contents of the OutputStream as an InputStream
public InputStream getInputStreamOfData(type param) {
// ..... data
OutputStreamWriter writer = new OutputStreamWriter();
writer.write(data);
// convert writer object to an InputStream
}
I came across some libraries to do this such as IOUtils and other thread based methods. Is there a simple way to achieve this using standard Java library ? I want to return the contents in the writer as an InputStream to be consumed by the calling method.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
写入
ByteArrayOutputStream
,然后获取字节数组,并从此字节数组返回ByteArrayInputStream
。Write to a
ByteArrayOutputStream
, then get the byte array, and return aByteArrayInputStream
from this byte array.我认为正确的方法是使用 PipedInputStream。它就像unix 管道(高级)。 PipedInputStream 构造函数接受 PipedOutputStream,因此如果您写入 PipedOutputStream,您将得到您想要的!
祝你好运!
I think the correct way to do it is using PipedInputStream. It's just like unix pipes (in highlevel). PipedInputStream constructor takes PipedOutputStream, so if you write to PipedOutputStream, you will get exactly what you want!
Good luck!