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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7099279/
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-10-30 18:37:19  来源:igfitidea点击:

Adding characters to beginning and end of InputStream in Java

javainputstreambufferedinputstream

提问by pqn

I have an InputStreamwhich 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?

我有一个InputStream我需要在开头和结尾添加字符,并且应该以另一个类型的变量结束InputStream。我怎么能轻易做到这一点?

回答by Tom Anderson

You want a SequenceInputStreamand a couple of ByteArrayInputStreams. You can use String.getBytesto make the bytes for the latter. SequenceInputStream is ancient, so it's a little clunky to use:

您需要一个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));

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 ReaderInputStreamfrom Commons IOto 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.

如果你有很多的字符添加,并且不希望将它们转换为字节集体,你可以把它们放在一个StringReader,然后用ReaderInputStream下议院IO读取它们以字节为单位。但是您需要将 Commons IO 添加到您的项目中才能做到这一点。确切的代码留给读者作为练习。

回答by rossum

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 InputStreamto 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.

1OutputStream按照 Greg 的建议,创建一个由字节数组支持的新..
2 将开始字符写入新的OutputStream.
3 将现有InputStreamOutputStream.
4 将结尾字符写入新的OutputStream.
5 关闭您的 new OutputStream,注意保留后备数组。
6 打开后备阵列作为一个新的InputStream

Let us know if you have a problem with any of these steps.

如果您对这些步骤中的任何一个步骤有问题,请告诉我们。