问题描述
我正在开发的程序使用 ADB(Android 调试桥)将文件发送到我的手机:
The program I'm working on uses ADB (Android Debug Bridge) to send files to my phone:
for (String s : files)
String cmd = "adb -s 0123456789ABCDEF push " + s + " /mnt/sdcard/" + s;
try {
InputStream is = Runtime.getRuntime().exec(cmd).getInputStream();
while (is.read() != -1) {}
} catch (IOException e) {
e.printStackTrace();
}
我希望程序一直等到 ADB 完成传输,但 ADB 作为守护进程运行,因此永远不会完成.但程序会立即继续,不知何故文件没有发送到我的手机(日志中没有例外).当我从控制台运行命令时,它可以正常工作.
I want the program to wait until ADB finished the transmission, but ADB runs as a daemon and therefore never finishes. But the program continues immideately and somehow the files aren't sent to my phone (no exceptions in log). When I run the command from console, it's working without problems.
我做错了什么?如何正确通过 ADB 发送文件?
What am I doing wrong? How do I send files via ADB correctly?
注意:is.read() == -1
将不起作用,因为 ADB 守护进程将所有输出写入系统标准输出.我试过将它转发到一个文本文件中.它保持为空,输出仍然写入终端
NOTE: the is.read() == -1
won't work, because the ADB daemon writes all output to the system standard output. I've tried forwarding it into a textfile. It stayed empty and the output was still written to the terminal instead
EDIT:读取 ADB 进程的 ErrorStream 返回每个 adb push
命令的 adb 帮助.再次:exact 命令(从 Eclipse 控制台复制)在终端中工作
EDIT: Reading the ErrorStream of the ADB process returned the adb help for each adb push
-command. Again: The exact commands (copied from Eclipse console) work in a terminal
EDIT 2:使用 ProcessBuilder 而不是 RUNtime.getRuntime.exec()
导致以下错误:
EDIT 2: Using a ProcessBuilder instead of RUntime.getRuntime.exec()
resulted in the following error:
java.io.IOException: Cannot run program "adb -s 0123456789ABCDEF push "inputfile "outputfile""": error=2, File or directory not found
在 ProcessBuilder 的 start()
方法中使用 ADB 的绝对路径 (/usr/bin/adb
) 时也会发生同样的情况.inputfile 和 outputfile 字符串也是绝对路径,如 /home/sebastian/testfile
并且肯定存在.从终端运行命令(打印字符串cmd",复制和粘贴)时,evreything 仍然可以正常工作.
at the ProcessBuilder's start()
-methodThe same happens when using an absolute path for ADB (/usr/bin/adb
). The inputfile and outputfile Strings are also absolute paths, like /home/sebastian/testfile
and definitely exist. When running the commands from terminal (string "cmd" printed, copy&paste), evreything still works fine.
推荐答案
我终于搞定了:
ProcessBuilder pb = new ProcessBuilder("adb", "-s", "0123456789ABCDEF", "push", inputfile, outputfile);
Process pc = pb.start();
pc.waitFor();
System.out.println("Done");
我不知道 ProcessBuilder
对字符串中的空格有什么问题,但最后,它正在工作...
I don't know what problems ProcessBuilder
has with spaces in a string, but finally, it's working...
这篇关于从 Java 程序执行 ADB 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!