【问题标题】:Why is OutputStream write method printed before PrintWriter's println method?为什么在PrintWriter的println方法之前打印OutputStream write方法?
【发布时间】:2021-08-07 01:54:13
【问题描述】:

我正在使用OutputStream 和PrintWriter。这是我的代码:

  OutputStream os = System.out;
  PrintWriter writer = new PrintWriter(os, false);

  writer.println("Hell");
  writer.println("Hello");
  writer.println("Hello");
  writer.println("Hello");
  writer.println("Hello");
  writer.println();
  os.write("45\n".getBytes(), 0, "45\n".getBytes().length);
  writer.println();
  writer.flush();
  os.flush();

输出是:

45
Hello
Hello
Hello
Hello
Hello

为什么45 在Hello 之前打印,即使PrintWriter 在OutputStream 之前被刷新?

编辑:如果我对冲洗有误,请纠正我。

【问题讨论】:

  • 刷新只影响缓冲流。如果流没有缓冲,则立即发送写入。

标签: java io java-io


【解决方案1】:

好吧,显然当你打电话给os.write() 时,你会得到一个PrintStream.write():

默认有autoFlush = true,而PrintWriter初始化为autoFlush=false。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多