从SD卡的文件夹中的文件复制到SD卡上的其他文件夹

问题描述:

是否有可能在SD卡复制文件夹present到另一个文件夹present相同的SD卡编程??

Is it possible to copy a folder present in sdcard to another folder present the same sdcard programmatically ??

如果是这样,那怎么办?

If so, how to do that?

这个例子的改进版本:

// If targetLocation does not exist, it will be created.
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {

    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists() && !targetLocation.mkdirs()) {
            throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
        }

        String[] children = sourceLocation.list();
        for (int i=0; i<children.length; i++) {
            copyDirectory(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {

        // make sure the directory we plan to store the recording in exists
        File directory = targetLocation.getParentFile();
        if (directory != null && !directory.exists() && !directory.mkdirs()) {
            throw new IOException("Cannot create dir " + directory.getAbsolutePath());
        }

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

有一些更好的错误处理和更好的手柄,如果传递的目标文件之处在于不存在的目录。

Got some better error handling and better handles if the passed target file lies in a directory that does not exist.