【问题标题】:I want to chain the"standard" output stream (System.out) to PrintWriter stream. But I can not. Why?我想将“标准”输出流(System.out)链接到 PrintWriter 流。但是我不能。为什么?
【发布时间】:2020-05-31 15:31:56
【问题描述】:

我想换掉:

System.out.println("It works properly");

作者:

PrintWriter myPrintWriter = new PrintWriter(System.out);
myPrintWriter.print("This text is not displayed on my screen");

不幸的是,第二个选项不起作用,我不知道为什么。我正在从头开始学习 Java,我正在尝试理解一些基本问题和概念,所以......请帮忙。对不起我的英语;)

【问题讨论】:

  • new PrintWriter(System.out, true);
  • 请注意,System.out 是一个 PrintStream,它与 PrintWriter 具有几乎相同的语义。所以new PrintWriter(System.out) 可能不是一件有用的事情。

标签: java stream chaining


【解决方案1】:

流不会自动刷新。使用myPrintWriter.flush() 在控制台获取结果。

演示:

import java.io.PrintWriter;

class Main {
    public static void main(String[] args) {
        PrintWriter myPrintWriter = new PrintWriter(System.out);
        myPrintWriter.print("This text is not displayed on my screen");
        myPrintWriter.flush();
    }
}

输出:

This text is not displayed on my screen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多