Background
In this post we will see how we can run any process from java programmatically. In specific I will show how can we compile a java file from a Java process. We can very well use Runtime.getRuntime().exec() method to start the process but in this post I am going to demonstrate using ProcessBuilder class.
Code
public static void executeJavacCommand() throws IOException {
List<String> paramsExecute = new ArrayList<String>();
paramsExecute.add("C:\\Program Files\\Java\\jdk1.6.0_31\\bin\\javac.exe");
paramsExecute.add("-cp");
paramsExecute.add(".");
paramsExecute.add("HelloWorld.java");
ProcessBuilder pBuilder = new ProcessBuilder(paramsExecute);
Process process = pBuilder.start();
Reader reader = new InputStreamReader(process.getErrorStream());
int ch;
while((ch = reader.read())!= -1)
System.out.print((char)ch);
reader.close();
}
Note1 : In above code I am only printing the error stream of the process but you can manipulate the output stream as well as provide input stream to the process.
Note 2: You can also see my previous post on how to get the java executable paths. You can programmatically derive those and use it in above code.
Note 2: You can also see my previous post on how to get the java executable paths. You can programmatically derive those and use it in above code.
No comments:
Post a Comment