我正在尝试编写一个从命令提示符下编译另一个Java文件的程序。我对此有疑问。至此,它已成功执行了第一部分,该部分将编译Mocha.java。但是,我希望它也执行该文件并显示其输出。它什么也不显示。有什么建议?
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"); }
注意:
我还尝试将所有参数初始化为:
pb = new ProcessBuilder("javac","Mocha.java","&&","java","Mocha");
但是,这不仅没有用,而且甚至没有像上面那样编译Mocha.java。
谢谢!
编辑:
因此,我将其更改为两个过程。现在工作棒!对于任何有兴趣的人:
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) { }
这是正常的:两个命令意味着两个进程。您需要两个ProcessBuilders,并在执行第二个过程之前检查第一个过程的返回值。
ProcessBuilder
这个语法:
new ProcessBuilder("javac","Mocha.java","&&","java","Mocha");
不起作用。&&是逻辑 外壳程序 运算符,javac命令不理解。而是直接在Java中执行处理逻辑:
&&
javac
if (p1.waitFor() == 0) // compile succeeded // initiate second process