复制目录以及目录下的文件和子目录到另一目录下(任何文件都可以拷贝)

使用递归思想,如果是文件就拷贝,一边读,一边写。如果是目录,就递归调用自己,详细请看代码。使用了FileInputStream,FileOutStream流。
如果想了解更多,请看这篇文章:一文搞定Java的输入输出流等常见流


public class CopyContent1 {
    public static void main(String[] args) {
//        拷贝源
        File srcFile = new File("F:\\QQ");
//        拷贝目标(放哪里)
        File destFile = new File("D:\\");
//        调用方法
        copyDir(srcFile,destFile);
    }

    private static void copyDir(File srcFile, File destFile) {
        if(srcFile.isFile()){//如果是文件递归结束
            /*是文件就拷贝,一边读,一边写*/
            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                //读
                in  = new FileInputStream(srcFile);
                //写
                String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" )+srcFile.getAbsolutePath().substring(3);

                out = new FileOutputStream(path);
                byte[] bytes = new byte[1024*1024];
                int readCount =0;
                while((readCount=in.read(bytes))!=-1){
                    out.write(bytes,0,readCount);//读多少写多少
                }
                out.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(in!=null){
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return;
        }
//        获取源的子目录
       File[] files=  srcFile.listFiles();
        for(File file :files){
            if(file.isDirectory()) {
//            获取所有文件的绝对路径
//            System.out.println(file.getAbsolutePath());
//            新建目标,对应的目录,将源目录除根目录外,其余加到目标目录后面
                String srcDir = file.getAbsolutePath();
                String destDir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" )+ srcDir.substring(3);
                File newFile = new File(destDir);
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
            }
//            字目录可能还是目录
            copyDir(file,destFile);
        }
    }
  }



在这里插入图片描述

发布了56 篇原创文章 · 获赞 33 · 访问量 5635

猜你喜欢

转载自blog.csdn.net/jiahuan_/article/details/105569131