< prev index next >

src/java.base/share/classes/java/io/OutputStream.java

Print this page
rev 48083 : [mq]: 4358774-nullISAndOS.01
rev 48082 : 4358774: Add null InputStream and OutputStream
Reviewed-by: XXX
rev 47920 : 8191516: OutputStream.write(byte[],int,int) could have fewer parameter bounds checks
Summary: Reduce parameter bounds checks from five to three as in InputStream::read
Reviewed-by: psandoz
rev 47216 : 8187443: Forest Consolidation: Move files to unified layout
Reviewed-by: darcy, ihse

@@ -45,10 +45,55 @@
  * @see     java.io.OutputStream#write(int)
  * @since   1.0
  */
 public abstract class OutputStream implements Closeable, Flushable {
     /**
+     * Returns a new {@code OutputStream} which discards all bytes.  The
+     * returned stream is initially open.  The stream is closed by calling
+     * the {@code close()} method.  Subsequent calls to {@code close()} have
+     * no effect.
+     *
+     * <p> While the stream is open, the {@code write(int)}, {@code
+     * write(byte[])}, and {@code write(byte[], int, int)} methods do nothing.
+     * After the stream has been closed, these methods all throw {@code
+     * IOException}.
+     *
+     * <p> The {@code flush()} method does nothing.
+     *
+     * @return an {@code OutputStream} which discards all bytes
+     *
+     * @since 10
+     */
+    public static OutputStream nullStream() {
+        return new OutputStream() {
+            private volatile boolean closed;
+
+            @Override
+            public void write(int b) throws IOException {
+                if (closed) {
+                    throw new IOException("Stream closed");
+                }
+            }
+
+            @Override
+            // overridden for efficiency
+            public void write(byte b[], int off, int len) throws IOException {
+                Objects.requireNonNull(b);
+                Objects.checkFromIndexSize(off, len, b.length);
+                if (closed) {
+                    throw new IOException("Stream closed");
+                }
+            }
+
+            @Override
+            public void close() {
+                closed = true;
+            }
+        };
+    }
+
+    /**
      * Writes the specified byte to this output stream. The general
      * contract for <code>write</code> is that one byte is written
      * to the output stream. The byte to be written is the eight
      * low-order bits of the argument <code>b</code>. The 24
      * high-order bits of <code>b</code> are ignored.
< prev index next >