Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compile & run java program in another java program?

People also ask

How do you compile a file?

If you want to just compile a specific file, right click on its name on the left listing of files, and select Compile Current Document. Once the compile is completed, the results are displayed on the Compiler Output tab at the bottom of the screen.

What is the compile process?

The compilation process is a set of stages that turns source code into executable object code.

How do I compile and run C code?

Step 1: Open turbo C IDE(Integrated Development Environment), click on File and then click on New. Step 2: Write the C program code. Step 3: Click on Compile or press Alt + F9 to compile the code. Step 4: Click on Run or press Ctrl + F9 to run the code.


I have modified the code to include some checks:

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

Here is the Main.java:

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

When everything is fine, it just works:

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

Now, for example, if I have some error in 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

It still prints "ok" because the previously compiled Main.class is still there, but at least you can see what exactly is happening when your processes are running.