Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 960
QY Lin Avatar asked Aug 08 '14 08:08

QY Lin


People also ask

What is runtime exec in Java?

exec(String command) method executes the specified string command in a separate process. This is a convenience method. An invocation of the form exec(command) behaves in exactly the same way as the invocation exec(command, null, null).

How does runtime getRuntime exec work?

getRuntime(). exec() method to use the command-line to run an instance of the program "tesseract". the first argument calls the tesseract program, the second is the absolute path to the image file and the last argument is the path and name of what the output file should be.

How do I run a terminal command in Java?

ProcessBuilder: Executing Command from Strings command("cmd", "/c", "dir C:\\Users"); Process process = processBuilder. start(); printResults(process); To actually execute a Process , we run the start() command and assign the returned value to a Process instance.


1 Answers

@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);
like image 154
QY Lin Avatar answered Sep 21 '22 21:09

QY Lin