Java CountingInputStream-class And Method Code Example


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

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.input.CountingInputStream;

class Example {
    public static void main(String[] args) {
        try (CountingInputStream cis = new CountingInputStream(new FileInputStream("file.txt"))) {
            byte[] buffer = new byte[1024];
            while (cis.read(buffer) != -1) {
                // do something with the read data
            }
            System.out.println("Bytes read: " + cis.getByteCount());
        } catch (IOException e) {
            // handle exception
        }
    }
}

This code creates a CountingInputStream which wraps a FileInputStream for the file "file.txt". It then reads data from the file using the read method and the number of bytes read is accumulated by the CountingInputStream. Finally, it prints the total number of bytes read from the file to the console using the getByteCount method.

The CountingInputStream provides a way to keep track of the number of bytes that have been read from an input stream without having to manually keep a count.