Java BrokenInputStream-class And Method Code Example

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


public class MyClass {
    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = new FileInputStream("example.txt");
        BrokenInputStream brokenInputStream = new BrokenInputStream(inputStream);
        brokenInputStream.setBroken(true); // set the stream to be broken
        int nextByte =;
        while (nextByte != -1) {
            // do something with the byte
            nextByte =;

In this example, BrokenInputStream is wrapping a FileInputStream for the file "example.txt".

It can be used to simulate a broken input stream by throwing an IOException when the read() method is called after the stream has been set to be broken by calling setBroken(true).

This allows to simulate the behavior of a broken stream, testing the exception handling of code that uses this stream.

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