Java BoundedReader-class And Method Code Example


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

import java.io.StringReader;
import java.io.IOException;
import org.apache.commons.io.input.BoundedReader;

public class MyClass {
    public static void main(String[] args) throws IOException {
        StringReader input = new StringReader("This is an example text");
        BoundedReader boundedReader = new BoundedReader(input, 5);

        int nextChar = boundedReader.read();
        while (nextChar != -1) {
            System.out.print((char)nextChar);
            nextChar = boundedReader.read();
        }
    }
}

In this example, BoundedReader is wrapping a StringReader that contains the string "This is an example text".

It limits the number of characters that can be read from the underlying reader to 5.

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

This will output:

This

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