如何在另一个java程序中编译和运行java程序?

我有一个Main.java和Test.java类,我想在Test.java代码中编译和运行Main.java。 这是我的代码

Process pro1 = Runtime.getRuntime().exec("javac Main.java"); pro1.waitFor(); Process pro2 = Runtime.getRuntime().exec("java Main"); BufferedReader in = new BufferedReader(new InputStreamReader(pro2.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } 

我只是在Main.java中打印“ok”,但是这个代码不打印任何东西。 问题是什么 ?

我修改了代码以包含一些检查:

 public class Laj { private static void printLines(String name, InputStream ins) throws Exception { String line = null; BufferedReader in = new BufferedReader( new InputStreamReader(ins)); while ((line = in.readLine()) != null) { System.out.println(name + " " + line); } } private static void runProcess(String command) throws Exception { Process pro = Runtime.getRuntime().exec(command); printLines(command + " stdout:", pro.getInputStream()); printLines(command + " stderr:", pro.getErrorStream()); pro.waitFor(); System.out.println(command + " exitValue() " + pro.exitValue()); } public static void main(String[] args) { try { runProcess("javac Main.java"); runProcess("java Main"); } catch (Exception e) { e.printStackTrace(); } } } 

这里是Main.java:

 public class Main { public static void main(String[] args) { System.out.println("ok"); } } 

当一切都很好,它只是工作:

 alqualos@ubuntu:~/tmp$ java Laj javac Main.java exitValue() 0 java Main stdout: ok java Main exitValue() 0 

现在,例如,如果我在Main.java中有一些错误:

 alqualos@ubuntu:~/tmp$ java Laj javac Main.java stderr: Main.java:3: package Systems does not exist javac Main.java stderr: Systems.out.println("ok"); javac Main.java stderr: ^ javac Main.java stderr: 1 error javac Main.java exitValue() 1 java Main stdout: ok java Main exitValue() 0 

它仍然打印“OK”,因为之前编译的Main.class仍然存在,但至less你可以看到当你的进程正在运行时究竟发生了什么。

你也需要

 pro2.waitFor(); 

因为执行该过程需要一些时间,并且在过程完成之前不能执行exitValue()。

我已经在Laj类的main函数中添加了条件来检查编译过程是否成功完成。

 public class Laj { private static void printLines(String name, InputStream ins) throws Exception { String line = null; BufferedReader in = new BufferedReader( new InputStreamReader(ins)); while ((line = in.readLine()) != null) { System.out.println(name + " " + line); } } private static int runProcess(String command) throws Exception { Process pro = Runtime.getRuntime().exec(command); printLines(command + " stdout:", pro.getInputStream()); printLines(command + " stderr:", pro.getErrorStream()); pro.waitFor(); // System.out.println(command + " exitValue() " + pro.exitValue()); return pro.exitValue(); } public static void main(String[] args) { try { int k = runProcess("javac Main.java"); if (k==0) k=runProcess("java Main"); } catch (Exception e) { e.printStackTrace(); } } }