Java BoundedInputStream-class And Method Code Example


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

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

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);
        BoundedInputStream boundedInputStream = new BoundedInputStream(inputStream, 5);

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

In this example, BoundedInputStream 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.

The BoundedInputStream is used in the same way as any other InputStream, in this case it reads a byte at a time until the end of the limit reached.

This will output:

1 2 3 4 5

Please note that this is a simple example and in real-world usage, you might want to do more complex processing on the bytes before returning them.