我怎样才能复制整个目录?

时间:2013-11-26 15:19:04

标签: java android copy-paste

我想复制整个目录onClick在android ..我怎么能这样做? 我有:

String sdCard = Environment.getExternalStorageDirectory().toString();
File srcFolder = new File(sdCard +"tryFirstFolder");
File destFolder = new File(sdCard +"/TryFolder");

然后我需要使用代码将srcFolder的全部内容复制到destFolder

1 个答案:

答案 0 :(得分:0)

您可以使用以下命令将目录从一个位置复制到另一个位置:

public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
        throws IOException {

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

        String[] children = sourceLocation.list();
        for (int i = 0; i < sourceLocation.listFiles().length; i++) {

            copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {

        InputStream in = new FileInputStream(sourceLocation);

        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

}

此链接也可以帮助您将文件从一个文件夹复制或移动到其他文件夹: http://www.codeofaninja.com/2013/04/copy-or-move-file-from-one-directory-to.html