使用进程构建器执行两个命令 [英] executing two commands with process builder

查看:44
本文介绍了使用进程构建器执行两个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个从命令提示符编译另一个 java 文件的程序.但是,我遇到了问题.至此,编译Mocha.java的第一部分成功执行.但是,我希望它也执行该文件并显示它输出的内容.它什么都不显示.有什么建议吗?

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");
    }

注意:

我也尝试像这样一开始就拥有所有参数:

I also tried to have all arguments initally like so:

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

但这不仅不起作用,它甚至没有像上面那样编译 Mocha.java.

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

谢谢!

所以我把这个改成两个进程.现在效果很好,伙计们!任何有兴趣的人:

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) {
    }

推荐答案

这是正常的:两个命令意味着两个进程.您需要两个ProcessBuilder,并在执行第二个之前检查第一个进程的返回值.

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.

这个语法:

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

不起作用.&& 是一个逻辑 shell 操作符,javac 命令不理解它.直接在 Java 中执行处理逻辑:

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

这篇关于使用进程构建器执行两个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆