一尘不染

如何在另一个java程序中编译和运行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”,但是此代码不打印任何内容。问题是什么 ?


阅读 501

收藏
2020-03-19

共1个答案

一尘不染

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

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仍然存在,但是至少您可以看到正在运行的进程究竟发生了什么。

2020-03-19