1

After having read a lot of similar questions about Runtime.exec and Java, I've not encountered a safe and clean idiom for compiling and running a .java file. I have just finished reading the "When Runtime.exec() won't" article, which helped me understand the general do's and don't's, but does not provide this idiom I'm looking for.

Overall I'm trying to create separate processes that will compile and run in series (multiple servers), without hanging or leaving any orphan processes. I'm not well-versed with these topics, so I am looking for more pointers.

So far I am able to compile the file by doing this:

try {            
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec("javac Server.java");
        int exitVal = proc.waitFor();
        System.out.println("Process exitValue: " + exitVal);

 } catch (Throwable t) {
        t.printStackTrace();
 }
  • 2
    You could use the `JavaCompiler` class, [for example](http://stackoverflow.com/questions/21544446/how-do-you-dynamically-compile-and-load-external-java-classes/21544850#21544850) – MadProgrammer Nov 30 '15 at 22:57
  • 1
    As a general rule; 1- Use `ProcessBuilder`, it's far more configurable; 2- Make sure you read and process the output stream of the `Process` – MadProgrammer Nov 30 '15 at 22:58
  • What is the use of reading and processing the output? – user5553362 Nov 30 '15 at 23:49
  • Some process stall if the output buffer is not read. It would also be useful to know if the process fails for some reason and why – MadProgrammer Nov 30 '15 at 23:50
  • See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and use a `ProcessBuilder` to create the process. – Andrew Thompson Dec 01 '15 at 19:38

0 Answers0