將A文件的內容複製到B文件

private static void fileCopy1(File from, File to){
        InputStream in = null;
        OutputStream out = null;

        try{

            //定義高效字節流
            in = new BufferedInputStream(new FileInputStream(from));
            out = new BufferedOutputStream(new FileOutputStream(to));
            //傳輸
            int b = 0;
            while((b = in.read())!=-1){
                out.write(b);
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                assert in != null;
                in.close();
                assert out != null;
                out.close();
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                in = null;
                out = null;
            }
        }
    }

    // 使用字符流複製,只能複製文本文件
    private static void fileCopy2(File from,File to){

        Reader r = null;
        Writer w= null;

        try{

            r = new BufferedReader(new FileReader(from));
            w = new BufferedWriter(new FileWriter(to));

            int b = 0;
            while((b = r.read())!=-1){
                w.write(b);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                assert r != null;
                r.close();
                assert w != null;
                w.close();
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                r = null;
                w = null;
            }
        }
    }

 

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