Class NoCloseOutputStream

java.lang.Object
java.io.OutputStream
org.apache.juneau.commons.io.NoCloseOutputStream
All Implemented Interfaces:
Closeable, Flushable, AutoCloseable

public class NoCloseOutputStream extends OutputStream
A wrapper around an OutputStream that prevents the underlying stream from being closed.

This class wraps an existing OutputStream and intercepts the close() method, making it a no-op (except for flushing). All other operations are delegated to the underlying stream. This is useful when you need to pass a stream to code that will close it, but you want to keep the underlying stream open for further use.

Features:
  • Prevents closing - close() flushes but doesn't close the underlying stream
  • Transparent delegation - all other operations pass through to the wrapped stream
  • Useful for resource management - allows multiple consumers without premature closing
Use Cases:
  • Passing streams to APIs that close them, but you need to keep the stream open
  • Multiple operations on the same stream where intermediate operations might close it
  • Resource management scenarios where you control the stream lifecycle
  • Wrapping system streams (System.out, System.err) that should not be closed
Usage:

// Wrap a stream that should not be closed FileOutputStream fos = new FileOutputStream("output.txt"); NoCloseOutputStream wrapper = new NoCloseOutputStream(fos); // Pass to code that might close it someMethod(wrapper); // May call close(), but fos remains open // Continue using the original stream fos.write("more data".getBytes()); fos.close(); // Close when actually done

Important Notes:
  • The close() method flushes the stream but does not close the underlying stream
  • You are responsible for closing the underlying stream when you're done with it
  • This wrapper does not prevent resource leaks - ensure the underlying stream is eventually closed
See Also:
  • Constructor Details

    • NoCloseOutputStream

      Constructor.

      Creates a new NoCloseOutputStream that wraps the specified OutputStream. The wrapper will prevent the underlying stream from being closed via the close() method.

      Example:

      FileOutputStream fos = new FileOutputStream("file.txt"); NoCloseOutputStream wrapper = new NoCloseOutputStream(fos);

      Parameters:
      os - The OutputStream to wrap. Must not be null.
  • Method Details