bytearrayoutputstream dataoutputstream分析

<span style="font-family: Arial; background-color: rgb(255, 255, 255);">DataOutputStream 類與BufferedOutputStream類的區別是什麼:</span>

BufferedOutputStream類能夠在內存裏建立一個緩衝區,當寫文件的時候,能起到緩衝的作用.但是DataOutputStream能像BufferedOutputStream類一樣起到緩衝作用嗎?如果有緩衝作用的話,但是DataOutputStream 類的構造函數裏,只有一個.而且其構造函數的參數沒有提供出設置緩存大小的參數? 

BufferedOutputStream類中構造對此類這樣定義:

 <pre name="code" class="java"> /**
     * Constructs a new {@code BufferedOutputStream}, providing {@code out} with a buffer
     * of 8192 bytes.
     *
     * @param out the {@code OutputStream} the buffer writes to.
     */
    public BufferedOutputStream(OutputStream out) {
        this(out, 8192);
    }

    /**
     * Constructs a new {@code BufferedOutputStream}, providing {@code out} with {@code size} bytes
     * of buffer.
     *
     * @param out the {@code OutputStream} the buffer writes to.
     * @param size the size of buffer in bytes.
     * @throws IllegalArgumentException if {@code size <= 0}.
     */
    public BufferedOutputStream(OutputStream out, int size) {
        super(out);
        if (size <= 0) {
            throw new IllegalArgumentException("size <= 0");
        }
        buf = new byte[size];
    }
代碼是這樣定義,當緩衝區的數據達到8192時候,纔會對緩衝區進行flush()操作,如果沒有達到該大小,手動調用flush()纔會成功!

<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">DataOutputStream 類中是這樣構造定義:</span>
<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"> /**
     * Constructs a new {@code DataOutputStream} on the {@code OutputStream}
     * {@code out}. Note that data written by this stream is not in a human
     * readable form but can be reconstructed by using a {@link DataInputStream}
     * on the resulting output.
     *
     * @param out
     *            the target stream for writing.
     */
    public DataOutputStream(OutputStream out) {
        super(out);
    }
</span>

沒有定義緩衝區的大小,也就是說緩衝區只要有數據都會flush()出來。

所以在常規情況下,

需要注意的是,如果採用什麼樣的流寫,必須採用對應的流讀。

爲了能夠提高讀寫效率,一次性把數據寫、讀。採用DataOutputStream。

針對file的寫、讀,使用DataOutputStream裝飾FileOutputStream;

針對byte的寫讀,使用DataOutputStream裝飾ByteArrayOutputStream。



發佈了32 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章