如何使用Runtime.getRuntime().exec("cmd")

ada*_*ack 5 java-native-interface android adb

在我的应用程序中,我正在尝试执行SD卡上的本机代码.

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);
Run Code Online (Sandbox Code Playgroud)

但是一旦Runtime.getRuntime().exec(cmd)执行,它就会抛出错误:

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
Run Code Online (Sandbox Code Playgroud)

有什么建议,如何解决?

cyg*_*ery 4

首先,您应该将调用包装到exec在 try-catch-子句中以捕获 IOException。

其次,使用exec(java.lang.String[])执行带参数的命令。例如,类似于

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