使用緩衝流複製一個文件

需求:

    使用緩衝字節流複製一個文件,要求邊讀邊寫,並處理異常。

直接上代碼:

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

        // 2.搭建數據通道
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;

        try {
            fileInputStream = new FileInputStream(readFile);
            bufferedInputStream = new BufferedInputStream(fileInputStream);

            fileOutputStream = new FileOutputStream(writeFile);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            // 3.讀寫數據
            int len = 0;
            /*byte[] bytes = new byte[1024];
            int content = bufferedInputStream.read(bytes, 0, bytes.length); */ //如果read讀取的文件數據傳入了緩衝數組,那麼讀取的內容存儲到緩衝數組中,返回值是存儲到緩衝數組中的字節數量。
            while ((len = bufferedInputStream.read()) != -1) { // 如果read讀取的文件數據沒有存儲到緩衝數組中,那麼返回值是讀取到的數據內容。注意:這裏說的緩衝數組是程序員自己維護的字節數組,不是緩衝流類中默認維護的8kb的數組。
                bufferedOutputStream.write(len);
            }

        } catch (FileNotFoundException e) {
            System.out.println("尋找目標文件發生異常......");
            throw new RuntimeException(e);
        } catch (IOException e) {
            System.out.println("讀寫數據發生異常......");
            throw new RuntimeException(e);
        } finally {
            // 4.關閉流資源
            try {
                System.out.println("關閉緩衝字節輸出流成功......");
                bufferedOutputStream.close();
                System.out.println("關閉緩衝字節輸入流成功......");
                bufferedInputStream.close();
            } catch (IOException e) {
                System.out.println("關閉流資源失敗......");
                throw new RuntimeException(e);
            }
        }
    }
}

 

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