当前位置:   article > 正文

android java echo,无法使用Runtime.exec()执行shell命令“ echo”。在Android Java代码中...

runtime.getruntime().exec 执行echo无效

I can use Runtime.exec() to execute shell commands like "getprop" and "ls system" and they work fine.

However, when I use "echo $BOOTCLASSPATH", "echo \\$BOOTCLASSPATH" or "echo HelloWorld", it won't show it in stdout.

The logcat shows:

I/AndroidRuntime( 4453): VM exiting with result code -1.

Here's my code:

try {

java.lang.Process proc = Runtime.getRuntime().exec("echo -e \\$BOOTCLASSPATH");

String line = null;

InputStream stderr = proc.getErrorStream();

InputStreamReader esr = new InputStreamReader (stderr);

BufferedReader ebr = new BufferedReader (esr);

while ( (line = ebr.readLine()) != null )

Log.e("FXN-BOOTCLASSPATH", line);

InputStream stdout = proc.getInputStream();

InputStreamReader osr = new InputStreamReader (stdout);

BufferedReader obr = new BufferedReader (osr);

while ( (line = obr.readLine()) != null )

Log.i("FXN-BOOTCLASSPATH", line);

int exitVal = proc.waitFor();

Log.d("FXN-BOOTCLASSPATH", "getprop exitValue: " + exitVal);

} catch (Exception e) {

e.printStackTrace();

}

解决方案

@Adi Tiwari, I've found the cause.

Runtime.getRuntime.exec() doesn't execute a shell command directly, it executes an executable with arguments.

"echo" is a builtin shell command. It is actually a part of the argument of the executable sh with the option -c.

Commands like ls are actual executables.

You can use type echo and type ls command in adb shell to see the difference.

So final code is:

String[] cmdline = { "sh", "-c", "echo $BOOTCLASSPATH" };

Runtime.getRuntime().exec(cmdline);

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号