NoCloseOutputStream.java

package net.morimekta.io;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Output stream that protects it's wrapped stream from being closed. Will still
 * be closable itself, but that will only prevent more writes.
 */
public class NoCloseOutputStream extends OutputStream {
    private final OutputStream  out;
    private final AtomicBoolean closed = new AtomicBoolean(false);

    /**
     * Create a no-close output stream.
     *
     * @param out The output stream to not close.
     */
    public NoCloseOutputStream(OutputStream out) {
        Objects.requireNonNull(out, "out == null");
        this.out = out;
    }

    @Override
    public void write(int b) throws IOException {
        if (closed.get()) {
            throw new IOException("Stream is closed");
        }
        out.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (closed.get()) {
            throw new IOException("Stream is closed");
        }
        out.write(b, off, len);
    }

    @Override
    public void write(byte[] b) throws IOException {
        if (closed.get()) {
            throw new IOException("Stream is closed");
        }
        out.write(b);
    }

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

    @Override
    public void close() throws IOException {
        closed.set(true);
    }
}