简体   繁体   English

Java中BufferedOutputStream的好处是什么? 每个OutputStream都没有缓冲区吗?

[英]What is the benefit of a BufferedOutputStream in java? Doesn't every OutputStream have a buffer?

my question is in some way similar to this one: what's the purpose of BufferedOutputStream? 我的问题在某种程度上类似于此: BufferedOutputStream的目的是什么? I have read the answers there, but there is still one thing I do not really understand: So in Java a BufferedOutputStream has an internal buffer. 我已经阅读了那里的答案,但是还有一件事我不太了解:所以在Java中,BufferedOutputStream有一个内部缓冲区。 And if this buffer is full or flush() is called, it writes the data to the underlying OutputStream (the one that was passed to the BufferedOutputStream's constructor). 而且,如果此缓冲区已满或调用了flush(),它将把数据写入底层的OutputStream(已传递给BufferedOutputStream的构造函数的数据)。 So far ok. 到目前为止,还可以。 But for me it looks, as if in fact any OutputStream would have such a buffer - as the base class OutputStream has a method flush(). 但对我来说,似乎实际上任何OutputStream都具有这样的缓冲区-因为基类OutputStream具有方法flush()。 The description of this method sais: "Flushes this output stream and forces any buffered output bytes to be written out." 该方法的描述说:“刷新此输出流并强制写出所有缓冲的输出字节。” So ... if all OutputStreams have a buffer, what is the benefit of a BufferedOutputStream then? 那么...如果所有OutputStreams都有一个缓冲区,那么BufferedOutputStream的好处是什么? Probably I am misunderstanding something ... can you please help me? 可能是我误会了某件事...您能帮我吗?

Greetings, Daniel 丹尼尔,问候

The base class OutputStream is abstract. 基类OutputStream是抽象的。 Meaning it defines the interface and some common behavior of all output streams. 这意味着它定义了接口以及所有输出流的一些常见行为。 You cannot instantiate OutputStream instance. 您不能实例化OutputStream实例。

The documentation clearly states that 该文档明确指出

The flush method of OutputStream does nothing. OutputStream的flush方法不执行任何操作。

It is up to the concrete implementation to determine whether or not it uses a buffer. 由具体实现决定是否使用缓冲区。

OutputStream has no buffer, you can check source code. OutputStream没有缓冲区,可以检查源代码。 BufferedOutputStream has its own buffer, its flush() writes bytes from own buffer to OS then flushes OS buffer. BufferedOutputStream有自己的缓冲区,其flush()将字节从自己的缓冲区写入OS,然后刷新OS缓冲区。 Why using BufferedOutputStream is more efficient - because OutputStream.write may call OS each time, which is expensive operation, and BufferedOutputStream.write puts bytes to buffer and calls OS only when buffer is full or on flush 为什么使用BufferedOutputStream效率更高-因为OutputStream.write可能每次都会调用OS,这是昂贵的操作,并且BufferedOutputStream.write会将字节放入缓冲区,并且仅在缓冲区已满或刷新时才调用OS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM