emon
1/8/2020 - 8:55 AM

Counting Outputstream: Guava

The class provides the additional method getCount() that returns the number of bytes written to the OutputStream

Source: https://www.baeldung.com/guava-counting-outputstream

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        CountingOutputStream cos = new CountingOutputStream(out);
 
        byte[] data = new byte[1024];
        ByteArrayInputStream in = new ByteArrayInputStream(data);
         
        int b;
        while ((b = in.read()) != -1) {
            cos.write(b);
            if (cos.getCount() >= MAX) {
                throw new RuntimeException("Write limit reached");
            }
        }