You can use Runtime class's method to execute the command like javac, java, etc. For example:
Process pro = Runtime.getRuntime().exec(command);
Where command is the String type argument, its value may be like "javac filename.java", "java class_name"
Following is the working program to Compile and run another java file. Suppose we have a java file named Main.java and we need to compile and run this file. Its source code is like following:
Main.java:
----------------------------------
public class Main {
public static void main(String[] args) {
System.out.println("This is Main class.");
}
}
And following is the java source code to compile and run the above file:
JavaCompiler.java:
-------------------------------------------
import java.io.*;
public class JavaCompiler {
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
private static int runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
return pro.exitValue();
}
public static void main(String[] args) {
try {
System.out.println("Compiling by javac Main.java....");
int k = runProcess("javac Main.java");
if (k==0){
System.out.println("Compiled Successfully....");
System.out.println("Running by java Main....");
k=runProcess("java Main");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now you just have to compile and run only JavaCompiler.java file by command prompt.
Output:
==========================
Download this example- Click Here