TerminatedOutputStream.java

package net.morimekta.io.sub;

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

/**
 * A wrapping output stream that writes a terminating byte when closing the
 * stream. It is meant to be paired with a {@link TerminatedInputStream},
 * which will terminate the wrapping stream as it at end of content when the
 * terminating byte is read.Note that the input behavior will be faulty if
 * the terminating byte is written to the output stream.
 */
public class TerminatedOutputStream extends OutputStream {
    private       OutputStream out;
    private final int          terminator;

    /**
     * Create a default instance terminating with a '00' byte.
     *
     * @param out Output stream to write terminator on close.
     */
    public TerminatedOutputStream(OutputStream out) {
        this(out, 0);
    }

    /**
     * Create a terminated output stream with specified terminator.
     *
     * @param out        Output stream to write terminator on close.
     * @param terminator Terminator byte code.
     */
    public TerminatedOutputStream(OutputStream out, int terminator) {
        if (terminator < 0 || terminator > 255) {
            throw new IllegalArgumentException("Invalid terminator byte: " + terminator);
        }
        this.out = out;
        this.terminator = terminator;
    }

    @Override
    public void write(int i) throws IOException {
        if (out == null) throw new IOException("Writing to closed stream");
        out.write(i);
    }

    @Override
    public void write(byte[] b) throws IOException {
        if (out == null) throw new IOException("Writing to closed stream");
        out.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (out == null) throw new IOException("Writing to closed stream");
        out.write(b, off, len);
    }

    @Override
    public void flush() throws IOException {
        if (out != null) {
            out.flush();
        }
    }

    @Override
    public void close() throws IOException {
        if (out != null) {
            out.write(terminator);
            out = null;
        }
    }
}