Java 緩衝流和flush()的作用 哪些流是緩衝流,哪些流帶有緩衝區? 根據Java官方文檔關於Buffered Streams的介紹,緩衝流有四種: BufferedInputStream:包裝位元組輸入流 BufferedOutputStream:包裝位元組輸出流 BufferedReader: ...
Java 緩衝流和flush()的作用
哪些流是緩衝流,哪些流帶有緩衝區?
根據Java官方文檔關於Buffered Streams的介紹,緩衝流有四種:
- BufferedInputStream:包裝位元組輸入流
- BufferedOutputStream:包裝位元組輸出流
- BufferedReader:包裝字元輸入流
- BufferedWriter:包裝字元輸出流
這些流又被稱為包裝流/處理流,用於包裝非緩衝的流
There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams.
——JAVA Documentation:Basic I/O
所以被包裝流包裝過的流都是使用緩衝區的;
緩衝流使用緩衝區;
位元組流預設不使用緩衝區;
字元流使用緩衝區。
flush()方法的作用
flush()
:沖洗緩衝區,強制將緩衝區中的數據全部寫入目標位置,清空緩衝區,不關閉流對象;
為什麼用flush():在使用Bufferd Streams輸出流對象時,我們需要對緩衝區進行沖洗,因為我們讀取數據時,數據會先被讀取在緩衝區中,為了確保輸出流中的數據被全部寫入,要flush緩衝區,否則數據會停留在緩衝區,不會輸出,導致數據損失;
flush() :To flush output stream, use void flush() method of DataOutputStream class. This method internally calls flush() method of underlying OutputStream class which forces any buffered output bytes to be written in the stream.
源自:https://stackoverflow.com/a/9272658/21906030
Flushing Buffered Streams
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. See Formatting for more on these methods.
.
To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered
——JAVA Documentation:Basic I/O