CountOutputStream

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 出力したバイト数を把握するためのStream。
 */
public class CountOutputStream extends FilterOutputStream {

    // カウンタ
    long[] bytes;

    /**
     * 内部でカウンタを保持するコンストラクタ。<br/>
     * カウンタ値は{@link #countBytes()}で取得する。
     */
    public CountOutputStream(OutputStream out) {
        this(out, null);
    }

    /**
     * カウンタの参照を指定するコンストラクタ。<br/>
     * refBytes[0]をカウンタとして使用する。<br/>
     * @param out
     * @param refBytes
     */
    public CountOutputStream(OutputStream out, long[] refBytes) {
        super(out);
        if (refBytes != null) {
            if (refBytes.length == 0) {
                throw new IllegalArgumentException("refBytes is empty");
            }
            bytes = refBytes;
        } else {
            bytes = new long[1];
        }
    }

    public void write(int b) throws IOException {
        out.write(b);
        bytes[0]++;
    }

    /**
     * カウンタの値を返す。
     * @return
     */
    public long countBytes() {return bytes[0];}

    /**
     * カウンタのリセット
     */
    public void reset() {bytes[0] = 0;}

}