Java 将目录文件复制到子文件夹中

Java 将目录文件复制到子文件夹中,java,Java,我想将文件从父目录复制到父目录的子文件夹中。现在我将复制的文件放入子文件夹,但每次都会重复,如果我已经复制了子文件夹和文件,它会一直重复,我希望它只复制一次 public static void main(String[] args) throws IOException { File source = new File(path2); File target = new File("Test/subfolder"); copyDirectory(source,

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

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

    }
}

您正在递归地调用您的方法,而没有中断递归的条件。您必须排除for循环中的目录。

您的程序在以下行中有问题

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

        }
    }

请重新表述你的问题和解释。这很难理解。Show可能会解决您的问题。在进行复制之前,请尝试验证else语句中是否存在“targetLocation”文件。请尝试查看以下内容: