gpt4 book ai didi

java - 在 PrintWriter 中,为什么 print() 函数不自动刷新?

转载 作者:搜寻专家 更新时间:2023-11-01 03:03:46 24 4
gpt4 key购买 nike

当查看以下构造函数的 PrintWriter 契约(Contract)时:

public PrintWriter(OutputStream out, boolean autoFlush)

Creates a new PrintWriter from an existing OutputStream. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.

Parameters:
out - An output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer

See Also: OutputStreamWriter.OutputStreamWriter(java.io.OutputStream)

请注意 autoFlush 标志仅适用于 printlnprintfformat。现在,我知道 printfformat 基本上做与 print 完全相同的事情,只是有更多选项,但我不明白为什么他们也没有在契约(Contract)中包括 print 。他们为什么做出这个决定?

最佳答案

我怀疑这是因为 Java 作者对性能做出了假设:

考虑以下代码:

public static void printArray(int[] array, PrintWriter writer) {
for(int i = 0; i < array.length; i++) {
writer.print(array[i]);
if(i != array.length - 1) writer.print(',');
}
}

您几乎肯定不希望这样的方法在每次调用后调用 flush()。这可能会对性能造成很大影响,尤其是对于大型阵列。而且,如果出于某种原因你确实想要这样做,你可以只调用 flush 你自己

想法是 printfformatprintln 方法可能会同时打印大量文本,所以在每个人之后冲洗是有意义的。但它很少(如果有的话)在仅 1 个或几个字符后刷新。


经过一番搜索,I have found a citation for this reasoning (强调我的):

Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

<snip>

It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.

Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format.

关于java - 在 PrintWriter 中,为什么 print() 函数不自动刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29754751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com