How to run an adb command through a Java file?

六眼飞鱼酱① 提交于 2019-12-19 04:58:35

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/17723922/how-to-run-an-adb-command-through-a-java-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!