1

How can I run multiple windows system commands (using Java) in order, with the second depending on the result of the first?

Like this:

adb.exe -s emulator-5554 shell
ls

and get the list result.

This is my source code, but it is not working:

public void connectToDevice(String device) {
    List<String> cmd = new ArrayList<String>();
    cmd.add("adb.exe -s " + device + " shell");
    cmd.add("ls");
    try {
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        Process process = pb.start();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}
4

1 回答 1

1

ProcessBuilder(List<String>)构造函数不打算并行运行多个命令。它将第一个元素列表作为命令,将后续元素作为其参数,因此实际执行的是adb.exe -s emulator-5554 shell ls一个命令。将其分为两个过程:

ProcessBuilder pb1 = new ProcessBuilder("adb.exe -s " + device + " shell");
pb1.redirectErrorStream(true);
Process p1 = pb1.start();
p1.waitFor();

ProcessBuilder pb2 = new ProcessBuilder("ls");
pb2.redirectErrorStream(true);
Process p2 = pb2.start();
p2.waitFor();
于 2013-02-03T00:19:10.450 回答