【问题标题】:Copy directory files into subfolder将目录文件复制到子文件夹中
【发布时间】:2014-07-25 13:11:22
【问题描述】:

我想将文件从父目录复制到父目录的子文件夹中。现在我将复制的文件放入子文件夹,但如果我已经复制了子文件夹和文件,它每次都会重复,它会一直重复,我希望它只男性一次

public static void main(String[] args) throws IOException {     
    File source = new File(path2);
    File target = new File("Test/subfolder");
    copyDirectory(source, target);
}
public static void copyDirectory(File sourceLocation, File targetLocation)
        throws IOException {
    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists()) {
            targetLocation.mkdir();
        }
        String[] children = sourceLocation.list();
        for (int i = 0; i < children.length; i++) {
            copyDirectory(new File(sourceLocation, children[i]), new File(
                    targetLocation, children[i]));
        }
    } else {
        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);
        byte[] buf = new byte[1];
        int length;
        while ((length = in.read(buf)) > 0) {
            out.write(buf, 0, length);
        }
        in.close();
        out.close();

    }
}

【问题讨论】:

  • 请重新表述您的问题和解释。很难理解。
  • 显示here可能会解决您的问题。
  • 在进行复制之前尝试验证 else 语句中是否存在“targetLocation”文件。

标签: java


【解决方案1】:

你的程序在下面一行有问题

String[] children = sourceLocation.list();

假设您的父目录 = Test 所以下面的代码会创建一个被测试的子文件夹

if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

之后,您将检索源文件夹的子文件夹,因为您的目标已经创建,它也将被视为源文件夹的子文件夹并递归地被复制。所以你需要先检索孩子,然后再创建目标目录,这样目标目录就不会被计算在复制过程中。 如下更改您的代码。

public static void main(String[] args) throws IOException {     
        File source = new File("Test");
        File target = new File("Test/subfolder");
        copyDirectory(source, target);
    }
    public static void copyDirectory(File sourceLocation, File targetLocation)
            throws IOException {

        String[] children = sourceLocation.list();
        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }
            for (int i = 0; i < children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]), new File(
                        targetLocation, children[i]));
            }
        } else {
            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetLocation);
            byte[] buf = new byte[1];
            int length;
            while ((length = in.read(buf)) > 0) {
                out.write(buf, 0, length);
            }
            in.close();
            out.close();

        }
    }

【讨论】:

    【解决方案2】:

    您在没有条件中断递归的情况下递归调用您的方法。您必须在 for 循环中排除目录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      相关资源
      最近更新 更多