Zobacz źródło PrintStream.
Ma dwa odniesienia do podstawowej wersji Writer textOut
i charOut
, jednej bazy znaków i jednego tekstu (cokolwiek to znaczy). Ponadto dziedziczy on trzecie odwołanie do strumienia wyjściowego opartego na bajtach, o nazwie out
.
/**
* Track both the text- and character-output streams, so that their buffers
* can be flushed without flushing the entire stream.
*/
private BufferedWriter textOut;
private OutputStreamWriter charOut;
W sposobie close()
zamyka wszystkie z nich (textOut
jest w zasadzie taka sama, jak charOut
).
private boolean closing = false; /* To avoid recursive closing */
/**
* Close the stream. This is done by flushing the stream and then closing
* the underlying output stream.
*
* @see java.io.OutputStream#close()
*/
public void close() {
synchronized (this) {
if (! closing) {
closing = true;
try {
textOut.close();
out.close();
}
catch (IOException x) {
trouble = true;
}
textOut = null;
charOut = null;
out = null;
}
}
}
Teraz, ciekawe jest to, że charOut zawiera (zawinięty) odwołuje się do samego PrintStream (uwaga init(new OutputStreamWriter(this))
w konstruktorze)
private void init(OutputStreamWriter osw) {
this.charOut = osw;
this.textOut = new BufferedWriter(osw);
}
/**
* Create a new print stream.
*
* @param out The output stream to which values and objects will be
* printed
* @param autoFlush A boolean; if true, the output buffer will be flushed
* whenever a byte array is written, one of the
* <code>println</code> methods is invoked, or a newline
* character or byte (<code>'\n'</code>) is written
*
* @see java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
*/
public PrintStream(OutputStream out, boolean autoFlush) {
this(autoFlush, out);
init(new OutputStreamWriter(this));
}
Więc wywołanie close()
wezwie charOut.close()
, co z kolei ponownie wywołuje oryginalny close()
, dlatego mamy flagę zamykającą, aby uciąć nieskończoną rekursję.
To coś, do czego służy debugger. Umieść punkt przerwania w metodzie zamykania i powinieneś być w stanie zobaczyć, dlaczego jest wywoływany. –