4

I have an InputStream of which I read data to log it on the screen. Then, this data I wish to pass it to an StaxParser. However the staxparser doesn't know to feed continuously from string,but rather input stream.

So I would like to clone the same inputstream to read both from it.

Do you have any better idea? If not, how can I clone the InputStreams?

Kind regards,

adragomir
  • 457
  • 4
  • 16
  • 33

2 Answers2

4

One way to "clone" the input stream would be the following: Note that you need to handle the exceptions :)

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1 ) {
    byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();

InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); 

Also reference How to clone an InputStream? for more options.

Community
  • 1
  • 1
imps
  • 1,423
  • 16
  • 22
2

You may store what you've read inside a String, then create an InputStream with it, and pass it to the parser :

InputStream is = new ByteArrayInputStream(srcString.getBytes());

Or, you have several ways to re-read from the same Stream, see here :

Read stream twice

Community
  • 1
  • 1
Arnaud
  • 17,229
  • 3
  • 31
  • 44