JAVA copy多级目录文件

package Iodemo;

import java.io.*;

public class CopyAllDemo {

    public static void main(String[] args) throws IOException {
        File f = new File("/Volumes/macdata/java_test/aa");
        File f2 = new File("./aa");
        //new_f2  "./"
        allCopy(f,f2);
    }
    public static void allCopy(File f,File new_f2) throws IOException {
        File[] files = f.listFiles();
        if (!new_f2.exists()){
            new_f2.mkdir(); //创建文件夹
        }
        for (File file:files){
            if (file.isDirectory()){  //如果是文件夹需要递归进行处理
                File  fs= new File(new_f2,file.getName());
                allCopy(file,fs);
            }else{
                String s = new_f2+"/" + file.getName();
                //根据这个目录去把文件写入
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream bos  = new BufferedOutputStream(new FileOutputStream(s));
                byte[] b = new byte[1024];
                int n;
                while ((n=bis.read(b))!=-1){
                    bos.write(b,0,n);
                    bos.flush();
                }
                bos.close();
                bis.close();
            }
        }
    }
}

 

posted @ 2022-04-05 13:05  phpwyl  阅读(57)  评论(0编辑  收藏  举报