我想将一个文件夹的所有内容复制到SDCard上的另一个文件夹中。我想在操作系统级别执行此操作。我尝试使用以下命令:cp -a/source/./dest/,这不起作用,它说权限被拒绝,因为我的设备没有植根。然而有趣的是,它允许我执行rm - r源
String deleteCmd = "rm -r " + sourcePath;
Runtime delete_runtime = Runtime.getRuntime();
try {
delete_runtime.exec(deleteCmd);
} catch (IOException e) {
Log.e("TAG", Log.getStackTraceString(e));
}
请告诉我是否有一种方法可以在操作系统级别实现此目的,否则我最后的手段将是此链接。提前谢谢。
经过更多的研究,我找到了适合我要求的完美解决方案。文件复制非常快。
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));
}
您的错误是"权限被拒绝",要么您没有执行"cp"二进制文件的权限,要么您没有在SD卡中创建目录的权限或许多其他可能出错的东西。
使用 adb shell 了解有关 cp 命令的更多信息,它位于/system/bin/中。
或
您可以下载终端模拟器应用程序并尝试从 shell 运行该命令。
使用 ls-l/system/bin 检查权限。
除此之外,不要忘记您的SD卡具有FAT文件系统,而cp -a使用chmod和utime的组合,这也超出了您的权限范围。而且我不是在谈论在 FAT fs 上做 chmod 不是一个好主意。除非您完全了解您在这里面临的问题,否则我还建议您使用您提供的链接。
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();
}
}