Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding characters to beginning and end of InputStream in Java

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?

like image 982
pqn Avatar asked Aug 17 '11 20:08

pqn


1 Answers

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.

like image 59
Tom Anderson Avatar answered Nov 09 '22 04:11

Tom Anderson