Well, I love java because the kind of solutions it provide for every programming or software related problem. Below program lets a user to compile and run a Java program and shows the output of program called. Yes it is, one program calling another program at run time.
Let the program to be executed as old our HelloWorld.java which prints a "Hello World" statement.
package myjava;
public class HelloWorld extends java.lang.Object{
private HelloWorld(){
}
/**
* @param args
*
*/
public static void main(String[] args) {
System.out.println("Hello World executed !!");
}
}
Save the above program in any location as HelloWorld.java in your m/c [say "D:\\MyJavaWorkspace\\Test\\src\\myjava\\HelloWorld.java"]
Even though static void main is mentioned in above program but instead of running and compiling this program here, it will be invoked from the below program. Following program is responsible for compiling & executing the above program
package myjava;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CompileOneProgramFromAnother {
/**
* @param args
*/
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime();
Process compileProcess = rt
.exec("javac D:\\MyJavaWorkspace\\Test\\src\\myjava\\HelloWorld.java");
System.out.println("CompileOneProgramFromAnother | HelloWorld.java Program is compiled successfully !!");
Process runProcess = rt
.exec("java -classpath D:\\MyJavaWorkspace\\Test\\src myjava.HelloWorld");
InputStreamReader isr = new InputStreamReader(
runProcess.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("********************OUTPUT of HelloWorld.java ***************\n");
while ((line = br.readLine()) != null)
System.out.println(line);
System.out.println("\n********************END OUTPUT of HelloWorld.java ***************");
int exitVal = runProcess.waitFor();
System.out.println("CompileOneProgramFromAnother | Process exitValue: " + exitVal);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
CompileOneProgramFromAnother | HelloWorld.java Program is compiled successfully !!
********************OUTPUT of HelloWorld.java ***************
Hello World executed !!
********************END OUTPUT of HelloWorld.java ***************
CompileOneProgramFromAnother | Process exitValue: 0
In above program, there are two processes created, one compiles the program and one executes the program. Inputs to both the programs are the commands used to compile & execute in Java.