从Java程序执行ADB命令

我正在使用的程序使用ADB(Android Debug Bridge)将文件发送到我的手机:

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作为守护进程运行,因此永远不会完成。 但该程序仍在继续,不知何故文件不会发送到我的手机(日志中没有例外)。 当我从控制台运行命令时,它没有问题。

我究竟做错了什么? 如何通过ADB正确发送文件?

注意: is.read() == -1将不起作用,因为ADB守护程序将所有输出写入系统标准输出。 我已经尝试将其转发到文本文件中。 它保持空白,输出仍然写入终端

编辑 :读取ADB流程的ErrorStream返回了每个adb push -command的adb帮助。 再次: 确切的命令(从Eclipse控制台复制)在终端中工作

编辑2 :使用ProcessBuilder而不是RUntime.getRuntime.exec()导致以下错误:

 java.io.IOException: Cannot run program "adb -s 0123456789ABCDEF push "inputfile "outputfile""": error=2, File or directory not found 

在ProcessBuilder的start() -method中使用ADB的绝对路径( /usr/bin/adb )时也是如此。 inputfile和outputfile Strings也是绝对路径,比如/home/sebastian/testfile ,肯定存在。 当从终端运行命令(字符串“cmd”打印,复制和粘贴)时,evreything仍然可以正常工作。

我用这种方式解决了:

 public class Utils { private static final String[] WIN_RUNTIME = { "cmd.exe", "/C" }; private static final String[] OS_LINUX_RUNTIME = { "/bin/bash", "-l", "-c" }; private Utils() { } private static  T[] concat(T[] first, T[] second) { T[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } public static List runProcess(boolean isWin, String... command) { System.out.print("command to run: "); for (String s : command) { System.out.print(s); } System.out.print("\n"); String[] allCommand = null; try { if (isWin) { allCommand = concat(WIN_RUNTIME, command); } else { allCommand = concat(OS_LINUX_RUNTIME, command); } ProcessBuilder pb = new ProcessBuilder(allCommand); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String _temp = null; List line = new ArrayList(); while ((_temp = in.readLine()) != null) { System.out.println("temp line: " + _temp); line.add(_temp); } System.out.println("result after command: " + line); return line; } catch (Exception e) { e.printStackTrace(); return null; } } } 

如果你的.bash_profile剪切“-l”参数中不需要env变量。

我有一台Mac,但它也适用于Linux。

我终于搞定了:

 ProcessBuilder pb = new ProcessBuilder("adb", "-s", "0123456789ABCDEF", "push", inputfile, outputfile); Process pc = pb.start(); pc.waitFor(); System.out.println("Done"); 

我不知道ProcessBuilder在字符串中有空格有什么问题,但最后,它正在工作……