Java ObservableInputStream-class And Method Code Example


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

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.input.ObservableInputStream;

class Example {
    public static void main(String[] args) {
        try (InputStream inputStream = new FileInputStream("file.txt")) {
            ObservableInputStream obs = new ObservableInputStream(inputStream);
            obs.addStreamListener(new StreamListener() {
                public void bytesRead(StreamEvent event) {
                    System.out.println("Bytes read: " + event.getBytes());
                }
                public void bytesSkipped(StreamEvent event) {
                    System.out.println("Bytes skipped: " + event.getBytes());
                }
                public void bytesWritten(StreamEvent event) {
                    System.out.println("Bytes written: " + event.getBytes());
                }
            });
            byte[] buffer = new byte[1024];
            int bytesRead = obs.read(buffer);
        } catch (IOException e) {
            // handle exception
        }
    }
}

This code creates an ObservableInputStream which wraps a FileInputStream for the file "file.txt". It then adds a StreamListener to the ObservableInputStream and reads data from the file using the read method.

As the data is read, the bytesRead method of the StreamListener is called and it prints the number of bytes read to the console.

The ObservableInputStream is a decorator for an input stream that allows you to add listeners to be notified of events that occur on the input stream, such as bytes being read, written or skipped.

It can be useful when you want to keep track of the number of bytes read, written, or skipped from an input stream without modifying the original code.