如何递归复制整个目录,包括Java中的父文件夹 [英] How to recursively copy entire directory including parent folder in Java

查看:452
本文介绍了如何递归复制整个目录,包括Java中的父文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将文件夹从一个地方复制到另一个地方。它工作正常,但它不是复制原始文件夹,所有其余的文件和文件夹也在其中。这是我使用的代码:

I am currently coping folders from one place to another. It is working fine out but it is not copying the original folder that all the rest of the files and folders are in over as well. This is the code I am using:

public static void copyFolder(File src, File dest) throws IOException {
  if (src.isDirectory()) {
    //if directory not exists, create it
    if (!dest.exists()) {
      dest.mkdir();
    }
    //list all the directory contents
    String files[] = src.list();
    for (String file : files) {
      //construct the src and dest file structure
      File srcFile = new File(src, file);
      File destFile = new File(dest+"\\"+src.getName(), file);
      //recursive copy
      copyFolder(srcFile,destFile);
    }
  } else {
    //if file, then copy it
    //Use bytes stream to support all file types
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dest); 
    byte[] buffer = new byte[1024];
    int length;
    //copy the file content in bytes 
    while ((length = in.read(buffer)) > 0){
      out.write(buffer, 0, length);
    }
    in.close();
    out.close();
    System.out.println("File copied from " + src + " to " + dest);
  }
}

所以我有这个文件夹src C:\test\mytest\...all folders ..

So I have the folder src C:\test\mytest\..all folders..

我想将其复制到 C:\test\myfiles

但不是得到 C:\test\myfiles\\ \\mytest\....all文件夹.. im get C:\test\myfiles\....all folders ..

But instead of getting C:\test\myfiles\mytest\..all folders.. im getting C:\test\myfiles\..all folders..

推荐答案

尝试使用 copyDirectory(File srcDir,File destDir)方法从 Apache Commons IO 库。

这篇关于如何递归复制整个目录,包括Java中的父文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆