何时/为什么在 Java 中调用 System.out.flush() [英] When/why to call System.out.flush() in Java

查看:30
本文介绍了何时/为什么在 Java 中调用 System.out.flush()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么需要刷新某些流(FileOutputStream 和来自 Sockets 的流)而标准输出流不需要?

Why do certain streams need to be flushed (FileOutputStream and streams from Sockets) while the standard output stream does not?

每次有人使用 System.out PrintStream 对象时,无论是在调用 println() 还是 write(),他们从不刷新流.但是,其他程序员习惯性地将 flush() 与其他流一起调用为 PrintStream/PrintWriter.

Every time someone uses the System.out PrintStream object, be it while calling println() or write(), they never flush the stream. However, other programmers habitually call flush() a PrintStream/PrintWriter with other streams.

我最近向几位程序员提出了这个问题,有些人认为 Java 中有一些后台处理可以自动刷新 System.out 流,但我找不到任何相关文档.

I've recently asked this question to several programmers and some believe that there is some background handling in Java to auto-flush the System.out stream but I can't find any documentation on that.

这样的事情让我想知道简单地调用 System.out.println() 是否是平台无关的,因为某些系统可能需要您刷新流.

Something like this makes me wonder if simply calling System.out.println() is platform independent as some systems may need you to flush the stream.

推荐答案

System.out 基于 PrintStream,默认情况下,每当写入换行符时都会刷新.

System.out is based around a PrintStream which by default flushes whenever a newline is written.

来自 javadoc:

autoFlush - 一个布尔值;如果为 true,则每当写入字节数组、调用 println 方法之一或换行符或字节 (' ') 时,都会刷新输出缓冲区写了

autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the println methods is invoked, or a newline character or byte (' ') is written

所以你提到的 println 情况被显式处理,并且带有 byte[]write 情况也保证刷新,因为它属于每当写入字节数组时".

So the println case you mention is explicitly handled, and the write case with a byte[] is also guaranteed to flush because it falls under "whenever a byte array is written".

如果您使用 System.setOut 并且不要使用自动刷新流,那么您必须像任何其他流一样刷新它.

If you replace System.out using System.setOut and don't use an autoflushing stream, then you will have to flush it like any other stream.

库代码可能不应该直接使用 System.out,但如果确实如此,则应该小心刷新,因为库用户可能会覆盖 System.out 使用非冲洗流.

Library code probably shouldn't be using System.out directly, but if it does, then it should be careful to flush because a library user might override System.out to use a non flushing stream.

任何将二进制输出写入 System.out 的 Java 程序都应该在 exit 之前小心 flush 因为二进制输出通常不包括尾随换行符.

Any Java program that writes binary output to System.out should be careful to flush before exit because binary output often does not include a trailing newline.

这篇关于何时/为什么在 Java 中调用 System.out.flush()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆