小能豆

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

javascript

I have a Main.java and Test.java classes that I want to compile and run Main.java in Test.java code. Here is my code

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

I just print “ok” in Main.java but this code doesn’t print anything. What is the problem ?


阅读 87

收藏
2023-11-22

共1个答案

小能豆

The issue might be related to how you’re trying to read the output of the java Main command. When you run a Java program using Runtime.getRuntime().exec("java Main"), the output of the Java program is typically not available through the input stream directly.

Instead of trying to read the output using pro2.getInputStream(), you might want to use ProcessBuilder and redirect the error stream as well. Here’s an example of how you could modify your code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder compileProcessBuilder = new ProcessBuilder("javac", "Main.java");
        Process compileProcess = compileProcessBuilder.start();
        compileProcess.waitFor();

        ProcessBuilder runProcessBuilder = new ProcessBuilder("java", "Main");
        runProcessBuilder.redirectErrorStream(true); // Redirect error stream to input stream
        Process runProcess = runProcessBuilder.start();

        printProcessOutput(runProcess.getInputStream());

        int exitCode = runProcess.waitFor();
        System.out.println("Exit code: " + exitCode);
    }

    private static void printProcessOutput(InputStream inputStream) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

This code uses ProcessBuilder to create separate processes for compiling and running the Java program. It also redirects the error stream to the input stream, and then reads and prints the output of the Java program. Additionally, it prints the exit code of the Java program.

2023-11-22