如何递归复制整个目录,包括Java中的父文件夹

new*_*ger 6 java directory

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

我想把它复制到 C:\test\myfiles

但不是让C:\test\myfiles\mytest\..all folders..我得到C:\test\myfiles\..all folders..

Jea*_*art 8

尝试使用Apache Commons IO库中的copyDirectory(File srcDir,File destDir)方法.

  • "你如何被复制"是什么意思? (6认同)