Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
338 views
Welcome To Ask or Share your Answers For Others

1 Answer

The general contract for OutputStream's close:

public void close() throws IOException Closes this output stream and releases any system resources associated with this stream. The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.

PrintStream's

public void close() Close the stream. This is done by flushing the stream and then closing the underlying output stream.

The 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:

public void write(String txt, OutputStream out) {
    PrintWriter printer = new PrintWriter(out);
    printer.print(txt);
    printer.flush();
    //it is very unpolite to close someone else's streams!
    //printer.close();
}

Oh, and by the way, you may want to change the function name to print, rather than write.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...