views:

53

answers:

2

A BufferedInputStream that I have isn't marking correctly. This is my code:

public static void main(String[] args) throws Exception {
    byte[] b = "HelloWorld!".getBytes();
    BufferedInputStream bin = new BufferedInputStream(new ByteArrayInputStream(b));
    bin.mark(3);
    while (true){
        byte[] buf = new byte[4096];
        int n = bin.read(buf);
        if (n == -1) break;
        System.out.println(n);
        System.out.println(new String(buf, 0, n));
    }
}

This is outputting:

11
HelloWorld!

I want it to output

3
Hel
8
loWorld!

I also tried the code with just a pure ByteArrayInputStream as bin, and it didn't work either.

+2  A: 

That's not what mark() does. You need to re-read the documentation. Mark lets you go backward through the stream.

dty
Thank you!!!!!!
Leo Izen
+4  A: 

I think you're misunderstanding what mark does.

The purpose of mark is to cause the stream to remember its current position, so you can return to it later using reset(). The argument isn't how many bytes will be read next -- it's how many bytes you'll be able to read afterward before the mark is considered invalid (ie: you won't be able to reset() back to it; you'll often end up at the start of the stream instead).

See the docs on InputStream for details. Readers' mark methods work quite similarly.

cHao
and make sure that `markSupported` returns true for whatever InputStream implementation you are using.
highlycaffeinated