Java CircularInputStream-class And Method Code Example


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

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

public class MyClass {
    public static void main(String[] args) throws IOException {
        byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
        CircularInputStream circularInputStream = new CircularInputStream(inputStream, 5);

        int nextByte = circularInputStream.read();
        while (nextByte != -1) {
            System.out.print(nextByte + " ");
            nextByte = circularInputStream.read();
        }
    }
}

In this example, CircularInputStream is wrapping a ByteArrayInputStream that contains the byte array { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }.

It limits the number of bytes that can be read from the underlying stream to 5.

Once the limit is reached, it starts reading again from the beginning.

The CircularInputStream is used in the same way as any other InputStream, in this case