Closing output stream 'misbehaving'?

In the following code:

    for(int i = 5; i  <= 100; i+=5)
    {
        linearSurprise(i); // Function calling 'System.out.print()'

        System.setOut(outStream); // Reassigns the "standard" output stream.

        System.out.println("Value of i: " + i); // Outputting the value to the .txt file.

        outStream.close(); // 'outStrem' is closed so that when I recall my function, output will 
                           // will be sent to the console and not file.

      // After debugging, I notice that nothing is being displayed to either the console or file, 
      // but everything else is still working fine. 
    }

I am calling a function 'linearSurprise' and in that function I output some information to the console. Once the function call is over, I redirect the value of 'i' to a text file. This works for the first iteration of the loop, but as soon as I call 'outStream.close()' no output whatsoever is displayed in the next iteration(console or file). Does anyone know why this is happening? Also what would be a workaround to this problem?

Jon Skeet
people
quotationmark

This assumption is invalid:

'outStrem' is closed so that when I recall my function, output will be sent to the console and not file.

Why would it magically go back to the console? It will just be written to a closed stream instead, which will cause an exception which is swallowed by PrintStream.

If you want to set it back to the original console stream, you need to do that explicitly:

PrintStream originalOutput = System.out;

// Do stuff...

System.setOut(originalOutput); // Now we can write back to the console again

people

See more on this question at Stackoverflow