0

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?

1
  • Which version of Java? 6 or 7? Commented Feb 28, 2014 at 18:01

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.