Class NoCloseOutputStream
- All Implemented Interfaces:
Closeable,Flushable,AutoCloseable
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:
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:
NoCloseWriter- Writer counterpart- I/O Package
-
Constructor Summary
Constructors -
Method Summary
Methods inherited from class java.io.OutputStream
nullOutputStream
-
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" ); NoCloseOutputStreamwrapper =new NoCloseOutputStream(fos );- Parameters:
os- The OutputStream to wrap. Must not benull .
-
-
Method Details
-
close
Flushes the stream but does not close the underlying OutputStream.This method flushes any buffered data to the underlying stream but does not close it. The underlying stream remains open and can continue to be used after this method is called.
Example:
FileOutputStream
fos =new FileOutputStream("file.txt" ); NoCloseOutputStreamwrapper =new NoCloseOutputStream(fos );wrapper .close();// Flushes but doesn't close fos fos .write("still works" .getBytes());// fos is still open - Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Overrides:
closein classOutputStream- Throws:
IOException- If an I/O error occurs while flushing.
-
flush
- Specified by:
flushin interfaceFlushable- Overrides:
flushin classOutputStream- Throws:
IOException
-
write
- Overrides:
writein classOutputStream- Throws:
IOException
-
write
- Overrides:
writein classOutputStream- Throws:
IOException
-
write
- Specified by:
writein classOutputStream- Throws:
IOException
-