Consider the following code-
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out);
out.println(1);
out.close();
}
}
I run it on bluej for the first time and get output 1 on console. On running it again i get no output at all and same is the case for any subsequent tries. Would love to know why this is happening.
Ok, the problem why this method only works once is, that the
PrintWriter.close()
method also closes the parent Stream, in this caseSystem.out
.So when you call this method the next time,
System.out
will be closed, and nothing will be printed.So the solution is not to close the
PrintWriter
.But in this case, nothing is printed, because the output of the
PrintWriter
is not flushed. To do that, you either have to callout.flush()
yourself or use a constructor which enables auto-flushing on line-endings.tl;dr:
Either use this:
or this: