Search code examples
javainputstreamreset

Can I perform successive mark operations on an InputStream in Java


I'm trying to build a simple parser, and since InputStream doesn't have some peek-like method, I'm using mark and reset. But I suspect that successive calls to mark, invalidate the previous ones. Is that the case? Is it possible to do something like

foo.mark(1);
...
foo.mark(2);
...
foo.reset();
...
foo.reset();

If not, is there some other way to simulate this or the peek method?

Thx.


Solution

  • Marks don't nest.

    If you want to reread the stream several times, you might need to copy (a portion of) the stream into a byte array, and make a ByteArrayInputStream of it. You still can't have multiple marks, but you can have multiple ByteArrayInputStreams. (Or just forget about ByteArrayInputStream and pick bytes off the array directly.)