欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将A文件的内容复制到B文件

程序员文章站 2022-07-09 22:34:56
...
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;
            }
        }
    }