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;

    public TerminatedOutputStream(OutputStream out) {
        this(out, 0);
    }

    public TerminatedOutputStream(OutputStream out, int 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, 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 {
        out.flush();
    }

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