ForkingOutputStream.java

package net.morimekta.io;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * The forking output stream is an output stream that will
 * write the same data to multiple streams. Each call will
 * be forked to each of the output streams. If any of the
 * calls throws {@link IOException}, then the method will
 * throw {@link IOException}, but will still attempt at
 * calling all the other streams before failing.
 */
public class ForkingOutputStream extends OutputStream {
    private final List<OutputStream> out;

    public ForkingOutputStream(OutputStream... out) {
        if (out == null || out.length == 0) {
            throw new IllegalArgumentException("No output");
        }
        this.out = new ArrayList<>(List.of(out));
    }

    public ForkingOutputStream(Collection<OutputStream> out) {
        if (out == null || out.isEmpty()) {
            throw new IllegalArgumentException("No output");
        }
        this.out = new ArrayList<>(out);
    }

    @Override
    public void write(int b) throws IOException {
        IOException ioe = null;
        for (OutputStream o : out) {
            try {
                o.write(b);
            } catch (IOException e) {
                if (ioe == null) ioe = e;
                else ioe.addSuppressed(e);
            }
        }
        if (ioe != null) {
            throw ioe;
        }
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        IOException ioe = null;
        for (OutputStream o : out) {
            try {
                o.write(b, off, len);
            } catch (IOException e) {
                if (ioe == null) ioe = e;
                else ioe.addSuppressed(e);
            }
        }
        if (ioe != null) {
            throw ioe;
        }
    }

    @Override
    public void close() throws IOException {
        IOException ioe = null;
        for (OutputStream o : out) {
            try {
                o.close();
            } catch (IOException e) {
                if (ioe == null) ioe = e;
                else ioe.addSuppressed(e);
            }
        }
        out.clear();
        if (ioe != null) {
            throw ioe;
        }
    }

    @Override
    public void flush() throws IOException {
        IOException ioe = null;
        for (OutputStream o : out) {
            try {
                o.flush();
            } catch (IOException e) {
                if (ioe == null) ioe = e;
                else ioe.addSuppressed(e);
            }
        }
        if (ioe != null) {
            throw ioe;
        }
    }
}