Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 537
Matthew Avatar asked Mar 04 '13 01:03

Matthew


2 Answers

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.

like image 40
Perception Avatar answered Oct 15 '22 13:10

Perception


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.

like image 83
user207421 Avatar answered Oct 15 '22 13:10

user207421