I was helping a friend to write some Java code, who doesn’t know a lot about Java. So I wrote him some helper functions to easily get things done that are a little quirky in his eyes. One of them is a function, that writes a String to an OutputStream. Have a look:
public void write(String txt, OutputStream out) {
PrintWriter printer = new PrintWriter(out);
printer.print(txt);
printer.close();
}
Now, you can use that easily in different ways to write wherever you want. For example you could do that:
(new StreamHelper()).write("Hello Test", System.out);
Doing that I found out that afterwards System.out.println() doesn’t write anything to the shell anymore. So I think that maybe printer.close() automatically also closed System.out and I wonder how to reactivate it that I can use it after this function is finished again.
Is my assumption correct? (How could I have found out without asking here?)
How can I continue to use System.out after a call to the write() function?
Are there better ways to write such a helper function?
The general contract for
OutputStream‘s close:PrintStream‘sThe only advice I can give you is that you should not write asymmetrical code, that is, don’t delegate the closing of resources your code has created to somewhere else.
Even if in your case it might seemed sensible to close the wrapper stream, the fact is that you should not because you are closing a stream opened somewhere else.
In short:
Oh, and by the way, you may want to change the function name to
print, rather thanwrite.