递归复制一个文件

package com.xiang;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MyCopyFilesUtil {
    //复制文件夹
    public void copyDir(String old,String xin){
        File file=new File(old);
        File file2=new File(xin);
        if(!file2.exists()){
            file2.mkdir();
        }
        File[] files=file.listFiles();
        for (int i = 0; i < files.length; i++) {
            if(files[i].isDirectory()){
                
    System.out.println(old+File.separator+files[i].getName());
                copyDir(old+File.separator+files[i].getName(), xin+File.separator+files[i].getName());
            }
        if(files[i].isFile()){
            try {
                copyFile(old+File.separator+files[i].getName(), xin+File.separator+files[i].getName());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                

            }
        }
    }
    //复制文件
    public void copyFile(String old,String xin) throws IOException{
        File f1=new File(old);
        File f2=new File(xin);
        FileInputStream fis=new FileInputStream(f1);
        FileOutputStream fos=new FileOutputStream(f2);
        int len=0;
        byte[] bs=new byte[1024];
        while((len=fis.read(bs))!=-1){
            fos.write(bs, 0, len);
        }
        fis.close();
        fos.close();
    }
}

 

posted @ 2021-05-10 09:29  傲云萧雨  阅读(55)  评论(0编辑  收藏  举报