将整个目录内容复制到另一个目录?

San*_* MS 63 java file-io grails groovy

将整个目录内容复制到java或groovy中的另一个目录的方法?

Jig*_*shi 89

FileUtils.copyDirectory()

将整个目录复制到保留文件日期的新位置.此方法将指定的目录及其所有子目录和文件复制到指定的目标.目标是目录的新位置和名称.

如果目标目录不存在,则创建目标目录.如果目标目录确实存在,则此方法将源与目标合并,并且源优先.

为此,这是示例代码

String source = "C:/your/source";
File srcDir = new File(source);

String destination = "C:/your/destination";
File destDir = new File(destination);

try {
    FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

  • 在我的情况下,我有一些子文件夹,我也想复制结构,并找到方法`FileUtils.copyDirectoryStructure()`.也许这也有助于其他人. (12认同)
  • JAVA API NIO 2怎么样?我试过`Files.copy(Path,Path)`但似乎没有做同样的工作. (2认同)
  • 导入org.apache.commons.io.FileUtils (2认同)

Arc*_*ano 31

以下是使用JDK7的示例.

public class CopyFileVisitor extends SimpleFileVisitor<Path> {
    private final Path targetPath;
    private Path sourcePath = null;
    public CopyFileVisitor(Path targetPath) {
        this.targetPath = targetPath;
    }

    @Override
    public FileVisitResult preVisitDirectory(final Path dir,
    final BasicFileAttributes attrs) throws IOException {
        if (sourcePath == null) {
            sourcePath = dir;
        } else {
        Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(final Path file,
    final BasicFileAttributes attrs) throws IOException {
    Files.copy(file,
        targetPath.resolve(sourcePath.relativize(file)));
    return FileVisitResult.CONTINUE;
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用访客,请执行以下操作

Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));
Run Code Online (Sandbox Code Playgroud)

如果你宁愿只是内联所有内容(如果你经常使用它,效率不高,但对于快速使用很有用)

    final Path targetPath = // target
    final Path sourcePath = // source
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path dir,
                final BasicFileAttributes attrs) throws IOException {
            Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(final Path file,
                final BasicFileAttributes attrs) throws IOException {
            Files.copy(file,
                    targetPath.resolve(sourcePath.relativize(file)));
            return FileVisitResult.CONTINUE;
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 我只是复制文件,他们是一个完整的应用程序与复制属性. (2认同)

tim*_*tes 15

使用Groovy,您可以利用Ant来执行:

new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
  fileset( dir:'/path/to/src/folder' )
}
Run Code Online (Sandbox Code Playgroud)

AntBuilder是发行版和自动导入列表的一部分,这意味着它可以直接用于任何groovy代码.

  • 你可能可以用Java,但就像使用大锤来破解核桃一样. (7认同)

kay*_*yz1 10

public static void copyFolder(File source, File destination)
{
    if (source.isDirectory())
    {
        if (!destination.exists())
        {
            destination.mkdirs();
        }

        String files[] = source.list();

        for (String file : files)
        {
            File srcFile = new File(source, file);
            File destFile = new File(destination, file);

            copyFolder(srcFile, destFile);
        }
    }
    else
    {
        InputStream in = null;
        OutputStream out = null;

        try
        {
            in = new FileInputStream(source);
            out = new FileOutputStream(destination);

            byte[] buffer = new byte[1024];

            int length;
            while ((length = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, length);
            }
        }
        catch (Exception e)
        {
            try
            {
                in.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }

            try
            {
                out.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你可以说我是老派,但很高兴在新行中看到大括号。我是一名前 C 和 C++ 程序员,尽管我已经用 Java 编写了 20 年,但我仍然会编写这样的代码。更具可读性! (3认同)

Gan*_*nus 7

这是我的一段 Groovy 代码。测试。

private static void copyLargeDir(File dirFrom, File dirTo){
    // creation the target dir
    if (!dirTo.exists()){
        dirTo.mkdir();
    }
    // copying the daughter files
    dirFrom.eachFile(FILES){File source ->
        File target = new File(dirTo,source.getName());
        target.bytes = source.bytes;
    }
    // copying the daughter dirs - recursion
    dirFrom.eachFile(DIRECTORIES){File source ->
        File target = new File(dirTo,source.getName());
        copyLargeDir(source, target)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @doelleri 在两点上更好 - 我不需要安装任何额外的 jars 或在 Maven 中放置引用,与版本斗争。顺便说一句,那个“答案”应该有适当的包含行和对 jar 的引用。第二个原因 - 如果我想在子目录中进行一些严格的过滤,只有我的代码会有所帮助。第三个原因——这里是程序员的站点,而不仅仅是软件用户。:-) (3认同)
  • 这比“FileUtils.copyDirectory()”更好吗? (2认同)

pla*_*nes 6

  • 澄清"Java 7:看看java.nio.file.Files" - 实际上没有回答这个问题 (15认同)
  • 虽然`Files.copy`支持目录,但它不会复制目录的内容. (5认同)
  • 阿帕奇是最好的。+1 (2认同)
  • @OhadR而不是"更好"我会说*更简单*. (2认同)