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

时间:2014-06-04 18:33:42

标签: java

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

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

    }
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

String [] children = sourceLocation.list();

假设你的父dir = 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();

        }
    }