无法使用PrintWriter在Bluej控制台中打印 [英] Unable to print in Bluej console using PrintWriter
问题描述
考虑以下代码-
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out);
out.println(1);
out.close();
}
}
我第一次在bluej上运行它,并在控制台上获得输出1.在再次运行它时,我根本没有任何输出,以后的尝试也是如此. 很想知道为什么会这样.
好,为什么此方法只能运行一次的问题是,PrintWriter.close()
方法也关闭了父Stream,在这种情况下为System.out
.>
因此,当您下次调用此方法时,System.out
将关闭,并且不会打印任何内容.
因此解决方案是不关闭PrintWriter
.
但是在这种情况下,不会打印任何内容,因为PrintWriter
的输出未刷新.为此,您必须自己调用out.flush()
或使用一个启用行尾自动刷新的构造函数.
tl; dr:
要么使用这个:
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out);
out.println(1);
out.flush();
}
}
或者这个:
import java.io.*;
public class test
{
public static void main(String[] args)
{
PrintWriter out= new PrintWriter(System.out, true);
out.println(1);
}
}
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 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);
}
}
这篇关于无法使用PrintWriter在Bluej控制台中打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!