How to compile and execute a Java file from within another Java Program
A few months ago I was tasked with writing a Java pseudo-compiler that would translate a made-up language, “One-T”, into Java. I guess what the teacher wanted was for me to create a stack that contained push and pop instructions and do all this complicated stuff. What I did instead was translate “One-T” into Java, and then compile it and execute it on the fly from within my Java program.
“How did Rommel did this trickery?,” you ask. Here is a snippet of code showing you how to compile AND execute a Java file from within a Java program.
[...]
import java.io.BufferedReader;
import java.io.InputStreamReader;
<strong>import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;</strong>
[...]
public class Generator {
[...]
//Simulates the generated Java code and returns the output to the screen.
public static void out(String outFile){
<strong>JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();</strong>
if(compiler.run(null, null, null, outFile+".java") != 0) {
System.err.println("Could not compile.");
System.exit(0);
}
try {
<strong>Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java "+outFile);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));</strong>
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}//end out.
[...]
} //end Generator
Geez, I hope I didn’t forget an import statement. Anyway, here is a little bit more explanation on the code.
First, we import the necessary tools from the Java library. Alternatively, you could just use
import javax.tools.*;
Second, we compile the program within our program, like so
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler.run(null, null, null, outFile+".java") != 0) {
System.err.println("Could not compile.");
System.exit(0);
}
where “outFile” is the name of the file we wish to compile. We generate an error message and exit if we cannot compile.
Third, we try to execute our recently compiled file:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java "+outFile);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
Finally, if we were successful we simply print the output to the screen. Otherwise, we catch the exception and display an error message.
I hope that was clear. Hit me up in the comments if you need further explanation.
Hi, my name is Rommel Rico. I work as a Sr. Programmer Analyst at the University of San Diego. My passions include entrepreneurship, computers, languages, football (soccer), art, reddit, theater, science fiction, classical music, aviation, running, and video games. At the moment, I'm really into StarCraft 2.
Nooshin
7 Dec, 2010
Hello there!
I have the same problem, I mean I have created my .class file and I want to execute this file and see the result. But I don’t know what is happening with the while loop that it never stops!
Even if I remove the while, In can not see the result. And I got a null pointer exception in this line :
compiler.run(null, null, null, outFile+”.java”
Any solution would be great
Thanks
Nooshin
Yogesh
29 Mar, 2011
its not giving swing result what can i do?
Rommel
29 Mar, 2011
I’m not talking about swing.
Divyansh
1 Apr, 2011
dude… i tried doing this, and it works perfectly…BUT:
i have some other class files in the same folder as the source file, that im using in my code. for some reason, the compiler gives me an error, saying that it could not find those classes.
note that im not creating objects of those classes.
can this be because i might have to have specify the path of the file?
nice post, btw!!
samira
18 Apr, 2011
it works perfectly.
Do you know how i can compile, and then run on a separate Java virtual machine?
Radhakrishnan
16 Aug, 2012
I could compile the other java file but could not execute it.it simply finishes the execution of current progrm with out running the nested compiled program.