Question

Here is what I have done:-

// compile
Runtime.getRuntime().exec("javac C:\\dir1\\dir2\\dir3\\Main.java");

// run
Runtime.getRuntime().exec("java C:\\dir1\\dir2\\dir3\\Main");

I am successfully able to compile this file but cannot run it. I have tried using exec("cd C:\\dir1\\dir2\\dir3") before using exec("java Main") but to no benefit. Any ideas?

Was it helpful?

Solution

Use a ProcessBuilder. Unlike Runtime.exec(), which you really should not use at all in modern code, a ProcessBuilder allows you to set up the directory in which the spawned process will run. Runtime.exec() does not give you this option.

Therefore:

final Path basePath = Paths.get("C:\\dir1\\dir2\\dir3");

final Process compileProcess = new ProcessBuilder("javac", "Main.java")
    .directory(basePath.toFile())
    // other niceties of ProcessBuilder
    .start();

// check the status of the process; rinse, repeat
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top