在Java中将字符添加到InputStream的开头和结尾
我有一个 InputStream
,我需要在其开头和结尾添加字符,并且应该以另一个 InputStream
类型的变量结束。我怎么能轻易做到这一点呢?
I have an InputStream
which I need to add characters to the beginning and end of, and should end up with another variable of type InputStream
. How could I easily do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要一个 SequenceInputStream 和几个 ByteArrayInputStream。您可以使用 String.getBytes 来制作后者的字节。 SequenceInputStream 很古老,所以使用起来有点笨拙:
如果您有很多字符要添加,并且不想将它们转换为字节全体,您可以将它们放在 StringReader,然后使用 ReaderInputStream 来自 Commons IO 将它们作为字节读取。但您需要将 Commons IO 添加到您的项目中才能做到这一点。确切的代码留给读者作为练习。
You want a SequenceInputStream and a couple of ByteArrayInputStreams. You can use String.getBytes to make the bytes for the latter. SequenceInputStream is ancient, so it's a little clunky to use:
If you have a lot of characters to add, and don't want to convert them to bytes en masse, you could put them in a StringReader, then use a ReaderInputStream from Commons IO to read them as bytes. But you would need to add Commons IO to your project to do that. Exact code for that is left as an exercise for the reader.
1 创建一个新的
OutputStream
,按照 Greg 的建议由字节数组支持..2 将开头字符写入新的
OutputStream
。3 将现有的
InputStream
复制到新的OutputStream
。4 将结束字符写入新的
OutputStream
。5 关闭新的
OutputStream
,注意保留后备数组。6 打开后备数组作为新的
InputStream
。如果您对这些步骤中的任何一个有疑问,请告诉我们。
1 Create a new
OutputStream
, backed by a byte array as Greg suggested..2 Write the beginning characters to your new
OutputStream
.3 Copy your existing
InputStream
to your newOutputStream
.4 Write the ending characters to your new
OutputStream
.5 Close your new
OutputStream
, taking care to preserve the backing array.6 Open the backing arrray as a new
InputStream
.Let us know if you have a problem with any of these steps.