Java MarkShieldInputStream-class And Method Code Example


Here is an example of how to use the MarkShieldInputStream class from the Apache Commons IO library in Java:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.commons.io.input.MarkShieldInputStream;

class Example {
    public static void main(String[] args) {
        byte[] data = new byte[] { 1, 2, 3, 4, 5 };
        try (MarkShieldInputStream msis = new MarkShieldInputStream(new ByteArrayInputStream(data))) {
            msis.mark(2);
            int b = msis.read();
            System.out.println(b); // 1
            b = msis.read();
            System.out.println(b); // 2
            msis.reset();
            b = msis.read();
            System.out.println(b); // 1
            msis.mark(0);
            b = msis.read();
            System.out.println(b); // 2
            b = msis.read();
            System.out.println(b); // 3
            msis.reset();
            b = msis.read();
            System.out.println(b); // 3
        } catch (IOException e) {
            // handle exception
        }
    }
}

This code creates a MarkShieldInputStream which wraps a ByteArrayInputStream containing the data. The mark method is used to set a mark at the current position in the stream, and the reset method is used to return to the marked position.

In this example, after reading the first two bytes, the stream is marked at position 2. Then we reset the stream, and it returns back to the mark position, which is the first byte. We read one byte and it returns 1.

Then we set the mark again at position 0, and read the next 2 bytes, the stream is now at position 2, we reset the stream and it returns to the mark position which is the first byte of the stream, the read method returns 3, since the mark has been changed to position 0 and we've already read the first two bytes.

It's important to note that the mark will be invalidated if more than the specified number of bytes are read after the mark has been set, it means that a mark is only valid for the number of bytes specified when the mark was set.