5.字節流的應用

需求:拷貝一份文件

    要求:

        1. 邊讀邊寫,不能將文件數據全部讀取完畢後,再寫出

        2. 處理程序可能出現的異常

   

    提示:

        1. 處理的異常的目的(步驟):
           (1)阻止下面代碼的執行(結束程序)
           (2)通知調用者這裏出現了錯誤
       

        2. throw RuntimeException(IOException e);
           (1) 將 IOException異常傳遞給 RuntimeException包裝一層,然後再拋出。這樣做的目的是爲了讓調用者使用變得更靈活。

           (2) RuntimeException運行時異常,出現這種異常時,jvm會自動阻斷後邊程序的運行,並將異常信息通知給調用者。

public class Dome1 {
    public static void main(String[] args) {
        // 1.找到目標文件
        File readFile = new File("E:\\aa\\bb\\aaaa.wmv");
        File writeFile = new File("E:\\aa\\bb\\複製品.wmv");

        // 2.搭建數據通道
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(readFile);
            fileOutputStream = new FileOutputStream(writeFile);

            // 3.傳輸數據
            byte[] bytes = new byte[1024];//構建緩衝數組讀取數據,緩衝數組的容量一般是1024的倍數
            int len = 0;//聲明變量,用於存儲每次讀取的數據
            while ((len = fileInputStream.read()) != -1) {//讀取文件內容
                //讀一次寫一次,len是每次讀寫的容量,FileOutputStream每次創建新的對象指針默認會指向文件的開始位置,同一個對象每次寫出時,指針會根據每次寫出,出現相應的移動。
                fileOutputStream.write(bytes, 0, len);//寫出,
            }
        } catch (IOException e) {
            /*
                處理的異常的目的(步驟):
                    1.阻止下面代碼的執行(結束程序)
                    2.通知調用者這裏出現了錯誤
                throw RuntimeException(IOException e);
                    將 IOException異常傳遞給 RuntimeException包裝一層,然後再拋出。這樣做的目的是爲了讓調用者使用變得更靈活。
                    RuntimeException運行時異常,出現這種異常時,jvm會自動阻斷後邊程序的運行,並將異常信息通知給調用者。
            */
            System.out.println("拷貝文件出錯......");
            throw new RuntimeException(e);//處理異常,將 fileNotFoundException異常包裝到運行時異常Runtimeexception中,當出現運行時異常時,會結束程序運行
        } finally {

            // 4.釋放資源
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                    System.out.println("關閉輸出流 fileOutputStream 資源成功......");
                }
            } catch (IOException e) {
                System.out.println("關閉輸出流 fileOutputStream 資源失敗......");
                throw new RuntimeException(e);
            } finally {
                try {
                    if (fileInputStream != null) {
                        System.out.println("關閉輸入流 FileInputStream 資源成功......");
                        fileInputStream.close();
                    }
                } catch (IOException e) {
                    System.out.println("關閉輸入流 FileInputStream 資源失敗......");
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

 

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