0

我想将一个文件夹的所有内容复制到 SDCard 上的另一个文件夹。我想在操作系统级别做到这一点。我尝试使用以下命令: cp -a /source/. /dest/,这不起作用,它说Permission Denied因为我的设备没有植根。然而有趣的是它允许我执行rm - r source

String deleteCmd = "rm -r " + sourcePath;
            Runtime delete_runtime = Runtime.getRuntime();
            try {
                delete_runtime.exec(deleteCmd);
            } catch (IOException e) {
                Log.e("TAG", Log.getStackTraceString(e));
            }

请告诉我是否存在一种方法可以在操作系统级别实现这一点,否则我最后的手段将是这个LINK。提前致谢。

4

3 回答 3

1

经过更多研究,我找到了适合我要求的完美解决方案。文件副本非常

mv命令对我来说很神奇,它将源文件夹中的所有文件移动到目标文件夹,并在复制后删除源文件夹。

String copyCmd = "mv " + sourcePath + " " + destinationPath;
Runtime copy_runtime = Runtime.getRuntime();
try {
        copy_runtime.exec(copyCmd);
     } catch (IOException e) {
        Log.d("TAG", Log.getStackTraceString(e));
     }
于 2014-01-09T07:41:03.670 回答
0

您的错误是“权限被拒绝”,要么您无权执行“cp”二进制文件,要么您无权在 sdcard 中创建目录或许多其他可能出错的东西。

使用 adb shell 了解更多关于 cp 命令的信息,它位于 /system/bin/。

或者

您可以下载终端仿真器应用程序并尝试从 shell 运行命令。

使用 ls -l /system/bin 检查权限。

除此之外,不要忘记您的 sdcard 具有 FAT 文件系统,而 cp -a 使用 chmod 和 utime 的组合,这也可能超出您的权限范围。而且我并不是说在 FAT fs 上执行 chmod 并不是一个好主意。除非您完全了解您在这里面临的问题,否则我还建议您使用您提供的链接。

于 2014-01-08T21:17:06.093 回答
-1
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();
    }
}
于 2014-01-06T11:07:30.630 回答