Search code examples
javasocketsiooutputstream

Is there a way to close a Writer without closing the underlying stream?


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?


Solution

  • 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.