I have a socket to which I write some character data, and some raw byte data. For the character data, it's easier to use a PrintWriter
. For the raw byte data, it's easier to write directly to the OutputStream
. So throughout my code, I have segments like this:
Writer writer = new PrintWriter(outputStream);
writer.write(someText);
...
writer.flush();
// No call to writer.close(), because that would close the underlying stream.
As long as I am careful not to write to this Writer
after beginning to write to the stream in some other way, this is fine. But I would prefer the safety of knowing that I'll get an IOException
if I accidentally do write to the stream (as I would if I had closed it).
Is there a way to explicitly prevent future writes to a Writer
without closing its underlying stream?
Simply put, no. The way Java io stream classes are written, they always chain close operations. You could of course, create your own writer implementation that overrode this behavior.
Why? close()
only does two things: (1) flush the writer and (2) call close()
on the nested writer. If you don't want (2), call flush()
yourself and don't call close()
at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With