在一种方法中,我尝试了两种输出到System.out
的方法:一种通过OutputStreamWriter
输出,另一种通过PrintWriter
输出。我发现只有前面的一个会输出,而后面的则不会输出。这是为什么?
是因为隐式关闭了第一个作家时,它还会关闭System.out
吗?
如何使两种方式(一个接一个)都输出?
try (BufferedWriter bw = new BufferedWriter (new PrintWriter(System.out, true))) // specify System.out for the output stream and "true" for automatic flushing.
{
bw.write("system.out->printwriter->bufferedwriter");
bw.write("\n");
// to make sure the content be printed.
// need to flush the output from the buffer to destination
// You can call flush or close
bw.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
try ( BufferedWriter bw2 = new BufferedWriter(new OutputStreamWriter(System.out)))
{
bw2.write("system.out->outputstreamwriter->bufferedwriter");
bw2.write("\n");
// need to flush the output from the buffer to destination
bw2.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
仅输出system.out->printwriter->bufferedwriter
try ( BufferedWriter bw2 = new BufferedWriter(new OutputStreamWriter(System.out)))
{
bw2.write("system.out->outputstreamwriter->bufferedwriter");
bw2.write("\n");
// need to flush the output from the buffer to destination
bw2.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter (new PrintWriter(System.out, true))) // specify System.out for the output stream and "true" for automatic flushing.
{
bw.write("system.out->printwriter->bufferedwriter");
bw.write("\n");
// to make sure the content be printed.
// need to flush the output from the buffer to destination
// You can call flush or close
bw.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
仅输出system.out->outputstreamwriter->bufferedwriter