使用两种方法输出到System.out,但是为什么只使用前面的输出呢?

时间:2019-05-26 10:46:31

标签: java io

在一种方法中,我尝试了两种输出到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

0 个答案:

没有答案