Runtime.getRuntime().exec: 为什么命令«cp»不起作用?



我的代码:

File dir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS );
File src = new File(dir, "test.dat");
File dst = new File(dir, "test_2.dat");
if ( src.exists() )
{
    try
    {
        Process process = Runtime.getRuntime().exec( new String[] {"cp", "-f", src.getAbsolutePath(), dst.getAbsolutePath()} );
        process.waitFor();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
}

此代码在三星Galaxy S3上有效(复制文件),但在亚马逊Kindle Fire:上无效

java.io.IOException:运行exec()时出错。命令:[cp,-f,/mnt/sdcard/Download/test.dat,/mnt/sdcard/Download/test_2.dat]工作目录:null环境:null

为什么会发生这种情况?如何在所有设备上执行此命令副本?

通常情况下,它不会工作,因为android应用程序没有访问下载目录的前提条件。或者可能是因为它无法访问/bin/cp。我想,如果你把手机拔掉,它会起作用的。从adb shell提示符尝试同样的操作,这样您就可以理解为什么它不起作用。

我在替换bootanimation.zip时也遇到过类似的问题,我就是这样解决的。希望它能帮助到别人。

Runtime.getRuntime().exec("mount -o remount,rw system /system");
Runtime.getRuntime().exec("cp /storage/emulated/0/bootanimation/bootanimation.zip /system/media/bootanimation.zip");
Runtime.getRuntime().exec("chmod 644 /system/media/bootanimation.zip");
Runtime.getRuntime().exec("mount -o remount,ro system /system");

最新更新