由java进程构建器运行多个命令,并通过bufferreader获取其输出

时间:2017-01-21 19:44:48

标签: java cmd

我正在运行以下代码:

public static void main(String[] args) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "echo hello");
    Process p = pb.start();


    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line, l = "";
    while ((line = bufferedReader.readLine()) != null) {

        System.out.println(l);
        l = l + line;

    }

    p.destroy();
    bufferedReader.close();
    System.out.println("completed");
    ProcessBuilder pb1 = new ProcessBuilder("cmd.exe", "/C", "echo hi");
    Process p1 = pb1.start();

    line = "";
    BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));

    while ((line = bufferedReader1.readLine()) != null) {

        l = l + line;
        System.out.println(l);

    }

    p1.destroy();
    bufferedReader1.close();
    System.out.println("completed");
}

但是在运行我的代码时,结果已被两个buffer-reader正确提取。

问题是程序的执行没有终止而且被挂起了。

1 个答案:

答案 0 :(得分:1)

为什么你没有创建一个方法来接收你的command并返回你的result,这样你可以执行许多命令,你可以在程序的每个地方使用它,如果您需要进行一些更改,只需更改此方法而不是所有程序:

您的代码应如此:

public static void main(String[] args) {
    String command1 = "echo hello";
    String command2 = "echo hi";
    System.out.println(executerCommand(command1));
    System.out.println(executerCommand(command2));
}

public static String executCommand(String command) {
    String line;
    String resultat = "";
    try {
        ProcessBuilder builder;

        builder = new ProcessBuilder("cmd.exe", "/c", command);

        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while (true) {
            line = r.readLine();
            if (line == null) {
                break;
            }
            resultat += line + "\n";
        }
    } catch (IOException e) {
        System.out.println("Exception = " + e.getMessage());
    }
    return resultat;
}

返回如下结果:

run:
hello

hi

BUILD SUCCESSFUL (total time: 0 seconds)

希望这可以帮到你