Java——文件複製異常處理

import java.io.*;
class test{
    public static void main(String[] args){
        //複製文件
        FileReader fr = null;
        FileWriter fw = null;

        try{
            fr = new FileReader("temp.txt");
            fw = new FileWriter("test_copy.txt");

            char[] arr = new char[1024];
            int num;

            while((num = fr.read(arr))!=-1){
                System.out.println(num);
                fw.write(arr,0,num);
            }
        }catch(IOException e){
            throw new RuntimeException("文件複製失敗");
        }
        finally{
            try{
                if(fr!=null){fr.close();}
            }catch(IOException e){
                throw new RuntimeException("讀取流關閉失敗");
            }
            try{
                if(fw!=null){fw.close();}
            }catch(IOException e){
                throw new RuntimeException("寫入流關閉失敗");
            }
        }
    }
}
發佈了89 篇原創文章 · 獲贊 211 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章