在Java中将字符添加到InputStream的开头和结尾

发布于 2024-11-30 06:28:12 字数 108 浏览 1 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

抠脚大汉 2024-12-07 06:28:12

您需要一个 SequenceInputStream 和几个 ByteArrayInputStream。您可以使用 String.getBytes 来制作后者的字节。 SequenceInputStream 很古老,所以使用起来有点笨拙:

InputStream middle ;
String beginning = "Once upon a time ...\n";
String end = "\n... and they lived happily ever after.";
List<InputStream> streams = Arrays.asList(
    new ByteArrayInputStream(beginning.getBytes()),
    middle,
    new ByteArrayInputStream(end.getBytes()));
InputStream story = new SequenceInputStream(Collections.enumeration(streams));

如果您有很多字符要添加,并且不想将它们转换为字节全体,您可以将它们放在 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:

InputStream middle ;
String beginning = "Once upon a time ...\n";
String end = "\n... and they lived happily ever after.";
List<InputStream> streams = Arrays.asList(
    new ByteArrayInputStream(beginning.getBytes()),
    middle,
    new ByteArrayInputStream(end.getBytes()));
InputStream story = new SequenceInputStream(Collections.enumeration(streams));

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.

拥醉 2024-12-07 06:28:12

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 new OutputStream.
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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文