【问题标题】:How to copy a folder and all its subfolders and files into another folder [duplicate]如何将文件夹及其所有子文件夹和文件复制到另一个文件夹中[重复]
【发布时间】:2011-07-19 03:08:20
【问题描述】:

如何将文件夹及其所有子文件夹和文件复制到另一个文件夹中?

【问题讨论】:

    标签: java


    【解决方案1】:

    选择你喜欢的:

    • 来自 Apache Commons IO 的 FileUtils(最简单和最安全的方式)

    FileUtils 示例:

    File srcDir = new File("C:/Demo/source");
    File destDir = new File("C:/Demo/target");
    FileUtils.copyDirectory(srcDir, destDir);
    

    Java 7 中的 AutoCloseable 功能示例:

    public void copy(File sourceLocation, File targetLocation) throws IOException {
        if (sourceLocation.isDirectory()) {
            copyDirectory(sourceLocation, targetLocation);
        } else {
            copyFile(sourceLocation, targetLocation);
        }
    }
    
    private void copyDirectory(File source, File target) throws IOException {
        if (!target.exists()) {
            target.mkdir();
        }
    
        for (String f : source.list()) {
            copy(new File(source, f), new File(target, f));
        }
    }
    
    private void copyFile(File source, File target) throws IOException {        
        try (
                InputStream in = new FileInputStream(source);
                OutputStream out = new FileOutputStream(target)
        ) {
            byte[] buf = new byte[1024];
            int length;
            while ((length = in.read(buf)) > 0) {
                out.write(buf, 0, length);
            }
        }
    }
    

    【讨论】:

    • 这是可行的,但如果发生异常,您将不会关闭流:您应该添加一个 try catch finally 块。
    • @Tim,这是真的。固定
    • copyFile 可以通过使用 Files#copy 方法来增强(因为它使用本地挂钩,如果可用的话)。
    • 出现错误。如果我想复制 1 个文件,它不起作用 - 因为 targeLocation 应该始终是一个文件夹,而在您的代码中,它始终用作 copyFile 中的文件。
    【解决方案2】:

    Apache Commons IO 可以为您解决问题。看看FileUtils。

    【讨论】:

    【解决方案3】:

    查看 java.io.File 中的一堆函数。

    您将遍历现有结构和 mkdir、保存等以实现深拷贝。

    【讨论】:

      【解决方案4】:

      JAVA NIO 将帮助您解决问题。请看看这个 http://tutorials.jenkov.com/java-nio/files.html#overwriting-existing-files.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-13
        • 2019-10-27
        • 1970-01-01
        • 2019-02-15
        • 1970-01-01
        • 1970-01-01
        • 2010-11-07
        • 2014-01-04
        相关资源
        最近更新 更多