问题
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.
回答1:
Ok, the problem why this method only works once is, that the PrintWriter.close()
method also closes the parent Stream, in this case System.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 call out.flush()
yourself or use a constructor which enables auto-flushing on line-endings.
tl;dr:
Either use this:
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out);
out.println(1);
out.flush();
}
}
or this:
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out, true);
out.println(1);
}
}
来源:https://stackoverflow.com/questions/49471270/unable-to-print-in-bluej-console-using-printwriter