是否可以通过编程将sdcard中存在的文件夹复制到存在相同sdcard的另一个文件夹中?

如果是这样,该怎么做?

最佳答案

该示例的改进版本:

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

如果传递的目标文件位于不存在的目录中,则可以得到更好的错误处理和更好的处理。

关于android - 将文件从SD卡的文件夹复制到SD卡的另一个文件夹,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5715104/

10-11 22:43
查看更多