7.BufferedOutputStream緩衝字節輸出流

7.BufferedOutputStream

1.輸出字節流

- - - - | OutputStream 輸出字節流的基類,抽象類

- - - - - - - - | FileOutputStream向文件輸出數據的 輸出字節流

- - - - - - - - | BufferedOutputStream緩衝輸出字節流。BufferedOutputStream出現的目的是爲了提高向文件輸出數據的效率。其內部維護了一個8kb(8192字節)的數組。

 

2.使用BufferedOutputStream的步驟:

  1. 找到目標文件

2. 搭建數據通道

3. 將數據寫出到BufferedOutputStream 維護的字節數組中

4. 將字節數組(內存)中的數據寫出到硬盤文件中。

 

3.BufferedOutputStream需要注意的細節

1. 在使用BufferedOutputStream寫數據的時候,它的write方法是將數據寫入到它內部維護的數組中的,而不是直接寫入到內存中。因爲BufferedOutputStream不具備向文件中寫入數據的能力。

2.使用BufferedOutputStream向文件寫入數據的三種情況

  首先使用BufferedOutputStream的write方法,將數據寫入到字節數組中(也就是內存中),從內存中寫入硬盤文件有3種情況:

   (1)使用flush方法,將內存中的數據刷入硬盤文件中。

   (2)使用close方法,將內存中的數據刷入硬盤文件中。其實它內部調用的是flush和close兩個方法,向將輸入flush刷入硬盤文件中,再關閉FileOutputStream流資源。

   (3)當字節數組已經填滿數據時(即字節數組已經存儲了8kb字節),它將會自動將數組中的數據刷入硬盤文件中。

4.案例

public class Dome2 {
    public static void main(String[] args) {
        // 1.找到目標文件
        File file = new File("E:\\aa\\bb\\BufferOutputStream.txt");

        // 2.搭建通道
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            // BufferedOutputStream
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            // 3.將數據寫出到BufferedOutputStream維護的字節數組中
            String str = "hello word!!!";//要寫入的數據
            byte[] bytes = str.getBytes();//將字符串轉換成字節數組
            bufferedOutputStream.write(bytes);//將字節輸入寫入到BufferedOutputStream內部維護的字節數組中
        } catch (FileNotFoundException e) {
            System.out.println("找尋文件發生異常......");
            throw new RuntimeException(e);
        } catch (IOException e) {
            System.out.println("寫出數據到內存中發生異常......");
            throw new RuntimeException(e);
        } finally {
            try {
                // 4.將字節數組中的數據寫出到硬盤文件中
                //fileOutputStream.flush();//將內存中數據刷入硬盤文件中
                bufferedOutputStream.close();//BufferedOutputStream的close方法內部,也是調用的flush方法
                /*
                    BufferedOutputStream的close方法的源碼:
                        public void close() throws IOException {
                            try (OutputStream ostream = out) {
                                flush();
                            }
                        }
                */
                // 當BufferedOutputStream內部維護的8kb的字節數組填充滿時,也會自動調用flush方法,將數據寫出到硬盤文件中。
            } catch (IOException e) {
                System.out.println("寫出內存中數據到硬盤發生異常......");
                throw new RuntimeException(e);
            }
        }
    }
}

總結:

    1. BufferedOutputStream的使用方法與BufferedInputStream的使用方法類似,只是BufferedOutputStream的write方法是將數據寫入到內部維護的字節數組中,而不是直接寫入到硬盤文件中。

    2. 從內存數組將數據寫入到硬盤文件,調用的plush方法與close方法效果相同,因爲close方法的內部其實也是調用了flush方法。

    3. BufferedInputStream 的筆記內容見上一篇: https://blog.csdn.net/qq_38082911/article/details/103951009

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章