Why does a local PrintWriter interfere with another local PrintWriter?

In this program, the third line is never printed. What for?

(This Java program was launched on Eclipse Indigo on Ubuntu 10.10.)

import java.io.PrintWriter;

public class Tester
{
    static void nested()
    {
        PrintWriter object2 = new PrintWriter(System.out, true);
        object2.println("second");
        object2.close(); // delete this line to make all strings print
    }

    public static void main(String[] args)
    {
        PrintWriter object1 = new PrintWriter(System.out, true);
        object1.println("first");
        Tester.nested();
        object1.println("third");
        object1.close();
    }
}
+5
source share
2 answers

By closing the nested PrintWriter, you also close the embedded stream System.out, which apparently prevents further writing to it (although I would really expect an exception instead of swallowing the output).

Thus, the whole problem can be reduced to:

public class Tester {

    public static void main(String[] args) {        
        System.out.println("first");
        System.out.close();
        System.out.println("second");        
    }
}

"", . Sun, .

Update *

: System.out java.io.PrintStream :

private void write(String s) {
    try {
        synchronized (this) {
            ensureOpen();
            textOut.write(s);
            textOut.flushBuffer();
            charOut.flushBuffer();
            if (autoFlush && (s.indexOf('\n') >= 0))
                out.flush();
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}

ensureOpen() , , trouble ( -). , .

+4

()

, .

, System.out , , . , System.out.println("Finished"); , System.out. .

+1

All Articles