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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/552621.html
標籤:其他
上一篇:java 獲取ip
下一篇:返回列表
