Unable to print in Bluej console using PrintWriter

假装没事ソ 提交于 2019-12-24 21:15:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!