16

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?

pqn
  • 1,494
  • 2
  • 22
  • 32

2 Answers2

37

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.

Tom Anderson
  • 42,965
  • 15
  • 81
  • 123
  • More detail please? Thanks for the handy class names. – pqn Aug 17 '11 at 20:53
  • 2
    If 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. – JB Nizet Aug 17 '11 at 21:00
  • Also, it should be `Arrays.asList` and not `Collections.asList`. – pqn Aug 17 '11 at 22:10
-1

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.

rossum
  • 14,325
  • 1
  • 19
  • 34
  • How do you write characters to an InputStream? – Tom Anderson Aug 17 '11 at 20:59
  • -1, Write the ending characters to your new InputStream. -> you can't write characters to an InputStream – GBa Aug 17 '11 at 21:00
  • Whoops! 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. – rossum Aug 17 '11 at 21:02
  • 2
    -1, this would've been better represented with code and isn't efficient for large streams. – Fabian Tamp Jul 07 '14 at 05:07
  • @Fabian I read this question as homework, hence I gave help, but not code. YMMV. – rossum Jul 11 '14 at 16:46