简体   繁体   English

如何通过 Java 文件运行 adb 命令?

[英]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.不确定这些信息是否有用,但我使用的是 Mac 并使用编辑器 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"结果是“线程“main”中的异常java.io.IOException:无法运行程序“adb”:错误=2,没有这样的文件或目录”

However, when I run the command "adb devicees" from the terminal I get the list of devices attached to my computer.但是,当我从终端运行命令“adb devicees”时,我会得到连接到我的计算机的设备列表。

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.您需要使用exec(String[] cmdarray)函数来发送参数,该函数的单参数版本会在空间上拆分字符串,如果您的路径包含空格,则会带来麻烦。

you also need to specify the full path (maybe /usr/bin/adb?).您还需要指定完整路径(也许是 /usr/bin/adb?)。

Like this:像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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