简体   繁体   中英

How to run an adb command through a Java file?

I have written the following code and cannot quite figure out how to solve the error. Not sure if this information will be found useful, but I am using a Mac and using the editor IntelliJ.

public class TestCode {
    public static void main(String[] args) throws Exception {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("adb devices");
    }
}

The result is "Exception in thread "main" java.io.IOException: Cannot run program "adb": error=2, No such file or directory"

However, when I run the command "adb devicees" from the terminal I get the list of devices attached to my computer.

For those interested, the following is the full stack trace.

Exception in thread "main" java.io.IOException: Cannot run program "adb": error=2, No such file or directory
    at java.lang.ProcessBuilder.processException(ProcessBuilder.java:478)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:457)
    at java.lang.Runtime.exec(Runtime.java:593)
    at java.lang.Runtime.exec(Runtime.java:431)
    at java.lang.Runtime.exec(Runtime.java:328)
    at com.sonos.acr.test.TestCode.main(TestCode.java:6)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:53)
    at java.lang.ProcessImpl.start(ProcessImpl.java:91)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
    ... 9 more

Thank you in advance for suggestions, advice, and/or help.

You need to use the exec(String[] cmdarray) function to send arguments, the single argument version of the function splits the string on space, and that spells trouble if your path contains spaces.

you also need to specify the full path (maybe /usr/bin/adb?).

Like this:

Process process = runtime.exec(new String[] {"/usr/bin/adb", "devices"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM