Java CountingOutputStream-class And Method Code Example


Here is an example of using the CountingOutputStream class from the org.apache.commons.io package in Java to count the number of bytes written to an OutputStream:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.io.output.CountingOutputStream;

public class CountingOutputStreamExample {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Create a CountingOutputStream to wrap the ByteArrayOutputStream
        CountingOutputStream cos = new CountingOutputStream(baos);

        // Write to the CountingOutputStream
        cos.write("Hello World!".getBytes());
        // Get the number of bytes written
        System.out.println("Bytes written: " + cos.getByteCount()); // "Bytes written: 12"
    }
}

In this example, a ByteArrayOutputStream is created and a CountingOutputStream is created to wrap it. The CountingOutputStream is then used to write "Hello World!" to the byte array and the method getByteCount() is used to get the number of bytes written to the output stream.

This class is useful when you need to keep track of the amount of data that is being written to an output stream. It can be used to monitor the progress of a file being written or to check if all the data was written successfully.