How to use Runtime.getRuntime().exec(“cmd”)

左心房为你撑大大i 提交于 2020-01-14 09:15:26

问题


In my application I'm trying to execute a native code which is present on my SD card.

File sdCard = getExternalFilesDir(null); // directory where native file is placed
String nativeFile = "nativeFile";

String cmd = "shell /system/bin/chmod 0777 " + sdCard.getAbsolutePath() + "/" + nativeFile;
Process proc = Runtime.getRuntime().exec(cmd);

But as soon as Runtime.getRuntime().exec(cmd) is executed, it throws error:

java.io.IOException: Error running exec(). Command: [shell, /system/bin/chmod, 0777, /storage/emulated/0/Android/data/com.example.andridutilproject/files/native] Working Directory: null Environment: null

Any suggestions, how to resolve this?


回答1:


First, you should wrap calls to exec in a try-catch-clause to catch IOExceptions.

Second, use exec(java.lang.String[]) to execute a command with parameters. For example, similar to

Runtime.getRuntime().exec(new String[]{ "shell", "/system/bin/chmod", "0777", sdCard.getAbsolutePath() + "/" + nativeFile });



回答2:


The sdcard in an Android system is usually disabled for execution. Therefore even if you correctly execute the chmod command it will fail.

You can test that easily. Start the shell via USB (adb shell) and execute the chmod command. It will fail with an error message like "Bad mode".

Therefore you have to copy the file to a different location where you have write access and then set the executable bit on that copy. You can try to copy the file for example to "/data/local/tmp/" but I am not sure if that path is still usable.



来源:https://stackoverflow.com/questions/26663604/how-to-use-runtime-getruntime-execcmd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!