TerminatedOutputStream.java

  1. package net.morimekta.io.sub;

  2. import java.io.IOException;
  3. import java.io.OutputStream;

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

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

  22.     /**
  23.      * Create a terminated output stream with specified terminator.
  24.      *
  25.      * @param out        Output stream to write terminator on close.
  26.      * @param terminator Terminator byte code.
  27.      */
  28.     public TerminatedOutputStream(OutputStream out, int terminator) {
  29.         if (terminator < 0 || terminator > 255) {
  30.             throw new IllegalArgumentException("Invalid terminator byte: " + terminator);
  31.         }
  32.         this.out = out;
  33.         this.terminator = terminator;
  34.     }

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

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

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

  50.     @Override
  51.     public void flush() throws IOException {
  52.         if (out != null) {
  53.             out.flush();
  54.         }
  55.     }

  56.     @Override
  57.     public void close() throws IOException {
  58.         if (out != null) {
  59.             out.write(terminator);
  60.             out = null;
  61.         }
  62.     }
  63. }