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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25199307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:33:51  来源:igfitidea点击:

Unable using Runtime.exec() to execute shell command "echo" in Android Java code

javaandroidshellechoruntime.exec

提问by QY Lin

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

我可以Runtime.exec()用来执行像“ getprop”和“ ls system”这样的shell命令,它们工作正常。

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

但是,当我使用“ echo $BOOTCLASSPATH”、“ echo \\$BOOTCLASSPATH”或“ echo HelloWorld”时,它不会在标准输出中显示。

The logcat shows:

logcat 显示:

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();
}

回答by QY Lin

@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 shwith the option -c. Commands like lsare actual executables. You can use type echoand type lscommand in adb shellto see the difference.
So final code is:

@Adi Tiwari,我找到了原因。 Runtime.getRuntime.exec()不直接执行 shell 命令,它执行带参数的可执行文件。" echo" 是一个内置的 shell 命令。它实际上是sh带有选项的可执行文件的参数的一部分-c。类似ls的命令是实际的可执行文件。您可以使用type echotype ls命令adb shell来查看差异。
所以最终的代码是:

String[] cmdline = { "sh", "-c", "echo $BOOTCLASSPATH" }; 
Runtime.getRuntime().exec(cmdline);