Adding characters to beginning and end of InputStream in Java
17,837
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.
Related videos on Youtube
Author by
pqn
Updated on June 05, 2022Comments
-
pqn almost 2 years
I have an
InputStream
which I need to add characters to the beginning and end of, and should end up with another variable of typeInputStream
. How could I easily do this? -
pqn over 12 yearsMore detail please? Thanks for the handy class names.
-
Tom Anderson over 12 yearsHow do you write characters to an InputStream?
-
Alex over 12 years-1, Write the ending characters to your new InputStream. -> you can't write characters to an InputStream
-
JB Nizet over 12 yearsIf you read the javadoc for those classes, it's pretty obvious. Construct a first ByteArrayInputStream (let's call it head) containing the bytes of the beginning, a second one containing the bytes of the end (let's call it tail), and build a SequenceInputStream from the head, the original input stream, and the tail.
-
rossum over 12 yearsWhoops! Reboots brain. Write to an output stream, backed by a byte array as Greg says. Extract the backing array and reopen as an input stream. Thanks for the correction.
-
pqn over 12 yearsAlso, it should be
Arrays.asList
and notCollections.asList
. -
Fabian Tamp almost 10 years-1, this would've been better represented with code and isn't efficient for large streams.
-
rossum almost 10 years@Fabian I read this question as homework, hence I gave help, but not code. YMMV.