Unable to print in Bluej console using PrintWriter

2019-08-18 02:35发布

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条回答
我只想做你的唯一
2楼-- · 2019-08-18 02:44

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);
    }
}
查看更多
登录 后发表回答