executing two commands with process builder

人盡茶涼 提交于 2019-12-02 10:12:46

问题


I'm trying to write a program that compiles another java file from the command prompt. I'm having an issue with it however. At this point, it is successfully executing the first part where it compiles Mocha.java. However, I want it to also execute that file and display what it outputs. It displays nothing. Any suggestions?

    pb = new ProcessBuilder("javac","Mocha.java");
    try {
        Process shell = pb.start();
        OutputStream shellOut = shell.getOutputStream();
        shellOut.write("java Mocha".getBytes());
        shellOut.close();
        InputStream shellIn = shell.getInputStream();
        String response = IOUtils.toString(shellIn, "UTF-8");
        System.out.println(response);
        shellIn.close();
        shell.destroy();
    } catch (IOException ex) {
        System.out.println("failed");
    }

Note:

I also tried to have all arguments initally like so:

pb = new ProcessBuilder("javac","Mocha.java","&&","java","Mocha");

But not only did this not work, it did not even compile Mocha.java as it did above.

Thanks!

EDIT:

So I changed this to make two processes. Works great now guys! For anyone interested:

    pb = new ProcessBuilder("javac","Mocha.java");
    try {
        Process shell = pb.start();
        int error = shell.waitFor();
        shell.destroy();
        if (error == 0)
        {
            pb = new ProcessBuilder("java","Mocha");
            shell = pb.start();
            InputStream shellIn = shell.getInputStream();
            String response = IOUtils.toString(shellIn, "UTF-8");
            System.out.println(response);
            shellIn.close();
            shell.destroy();
        }
    } catch (IOException ex) {
        System.out.println("failed");
    } catch (InterruptedException ex) {
    }

回答1:


This is normal: two commands mean two processes. You need two ProcessBuilders, and check the return value of the first process before executing the second one.

This syntax:

new ProcessBuilder("javac","Mocha.java","&&","java","Mocha");

does not work. && is a logical shell operator, the javac command does not understand it. Do your processing logic in Java directly instead:

if (p1.waitFor() == 0) // compile succeeded
    // initiate second process



回答2:


The syntax mentioned works with shell, not with java ProcessBuilder.

Option one is to launch shell and execute shell command. Another is to invoke to ProcessBuilder two times. One for javac another for java



来源:https://stackoverflow.com/questions/17216049/executing-two-commands-with-process-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!