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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11651900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:55:50  来源:igfitidea点击:

How to recursively copy entire directory including parent folder in Java

javadirectory

提问by newSpringer

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);
  }
}

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

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

I want to copy it to C:\test\myfiles

我想复制到 C:\test\myfiles

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

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

回答by Jean Logeart

Try using the copyDirectory(File srcDir, File destDir)method from the Apache Commons IOlibrary instead.

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

回答by jan.supol

There is a tutorial for copying files using java.niowith a recursive copy example code on Oracle Docs. It works with java se 7+. It uses Files.walkFileTree method, which might cause some issues on ntfs with junction points. To avoid using Files.walkFileTree, the possible solution can look like:

在 Oracle Docs 上有一个使用 java.nio 复制文件和递归复制示例代码教程。它适用于 java se 7+。它使用 Files.walkFileTree 方法,这可能会在带有连接点的 ntfs 上引起一些问题。为避免使用 Files.walkFileTree,可能的解决方案如下所示:

public static void copyFileOrFolder(File source, File dest, CopyOption...  options) throws IOException {
    if (source.isDirectory())
        copyFolder(source, dest, options);
    else {
        ensureParentFolder(dest);
        copyFile(source, dest, options);
    }
}

private static void copyFolder(File source, File dest, CopyOption... options) throws IOException {
    if (!dest.exists())
        dest.mkdirs();
    File[] contents = source.listFiles();
    if (contents != null) {
        for (File f : contents) {
            File newFile = new File(dest.getAbsolutePath() + File.separator + f.getName());
            if (f.isDirectory())
                copyFolder(f, newFile, options);
            else
                copyFile(f, newFile, options);
        }
    }
}

private static void copyFile(File source, File dest, CopyOption... options) throws IOException {
    Files.copy(source.toPath(), dest.toPath(), options);
}

private static void ensureParentFolder(File file) {
    File parent = file.getParentFile();
    if (parent != null && !parent.exists())
        parent.mkdirs();
} 

回答by Igor G.

And of course springhas that covered also with FileSystemUtils.copyRecursively(File src, File dest)

当然,spring也涵盖了FileSystemUtils.copyRecursively(File src, File dest)

回答by stillwaiting

Using java.nio:

使用 java.nio:

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public static void copy(String sourceDir, String targetDir) throws IOException {

    abstract class MyFileVisitor implements FileVisitor<Path> {
        boolean isFirst = true;
        Path ptr;
    }

    MyFileVisitor copyVisitor = new MyFileVisitor() {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            // Move ptr forward
            if (!isFirst) {
                // .. but not for the first time since ptr is already in there
                Path target = ptr.resolve(dir.getName(dir.getNameCount() - 1));
                ptr = target;
            }
            Files.copy(dir, ptr, StandardCopyOption.COPY_ATTRIBUTES);
            isFirst = false;
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path target = ptr.resolve(file.getFileName());
            Files.copy(file, target, StandardCopyOption.COPY_ATTRIBUTES);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            throw exc;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Path target = ptr.getParent();
            // Move ptr backwards
            ptr = target;
            return FileVisitResult.CONTINUE;
        }
    };

    copyVisitor.ptr = Paths.get(targetDir);
    Files.walkFileTree(Paths.get(sourceDir), copyVisitor);
}

回答by Sujay

You can try out Apache FileUtilsto copy directories as well

您也可以尝试使用Apache FileUtils来复制目录

回答by Arvik

回答by tibtof

The main problem is this:

主要问题是这样的:

  dest.mkdir();

only create one directory, not the parent one, and after the first step you need to create two directories, so replace mkdirwith mkdirs. After that I guess that you'll have duplicate child directories because of your recursion (something like C:\test\myfiles\mytest\dir1\dir1\subdir1\subdir1...), so also try to fix this lines:

只创建一个目录,而不是父目录,第一步后需要创建两个目录,所以替换mkdirmkdirs. 在那之后,我猜你会因为递归而有重复的子目录(类似于 C:\test\myfiles\mytest\dir1\dir1\subdir1\subdir1...),所以也尝试修复以下几行:

    File destFile = new File(dest, src.getName());
    /**/
    OutputStream out = new FileOutputStream(new File(dest, src.getName())); 

回答by user3222748

This code copies a folder from source to destination:

此代码将文件夹从源复制到目标:

    public static void copyDirectory(String srcDir, String dstDir)
    {

        try {
            File src = new File(srcDir);
            String ds=new File(dstDir,src.getName()).toString();
            File dst = new File(ds);

            if (src.isDirectory()) {
                if (!dst.exists()) {
                    dst.mkdir();
                }

                String files[] = src.list();
                int filesLength = files.length;
                for (int i = 0; i < filesLength; i++) {
                    String src1 = (new File(src, files[i]).toString());
                    String dst1 = dst.toString();
                    copyDirectory(src1, dst1);

                }
            } else {
                fileWriter(src, dst);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public static void fileWriter(File srcDir, File dstDir) throws IOException
{
        try {
            if (!srcDir.exists()) {
                System.out.println(srcDir + " doesnot exist");
                throw new IOException(srcDir + " doesnot exist");
            } else {
                InputStream in = new FileInputStream(srcDir);
                OutputStream out = new FileOutputStream(dstDir);
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();

            }
        } catch (Exception e) {

        }
    }