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;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
[...]
public class Generator {
[...]
//Simulates the generated Java code and returns the output to the screen.
public static void out(String outFile){
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler.run(null, null, null, outFile+".java") != 0) {
System.err.println("Could not compile.");
System.exit(0);
}
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java "+outFile);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
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?
pakar digital marketing
28 Feb, 2012
Very interesting info !Perfect just what I was searching for! “We are shaped and fashioned by what we love.” by Johann von Goethe.
Anja Knapke
8 Mar, 2012
It is really a great and useful piece of info. I’m glad that you shared this useful info with us. Please keep us informed like this. Thank you for sharing.
nsp 1212
9 Mar, 2012
I like this blog very much, Its a very nice post to read and get info . “Famous remarks are very seldom quoted correctly.” by Simeon Strunsky.
Cathie Mccrane
9 Mar, 2012
I genuinely enjoy examining on this site, it holds wonderful blog posts.
URL
11 Mar, 2012
Thank you for the auspicious writeup. It in truth used to be a amusement account it. Glance complex to much more added agreeable from you! Nevertheless, how could we be in contact? 879201
เกมส์ xshot
12 Mar, 2012
This can indicate that a watch has spent some or all of its life inside the tropics and was not serviced as regularly as it really should have been. 607724
Mens Fitness
15 Mar, 2012
Do you never quit! This can be the most effective weblogs Ive actually examine. You have several upset ability the following, gentleman. I merely expect that you dont get rid of your thing because you happen to be one of the hottest blog writers out there. Please continue as the internet requires someone like you spreading the word.
Mania contents
19 Mar, 2012
Everything is very open with a very clear description of the challenges. It was definitely informative. Your website is extremely helpful. Many thanks for sharing!
Tarzan vibrator
19 Mar, 2012
The electronic cigarette uses a battery and a small heating factor the vaporize the e-liquid. This vapor can then be inhaled and exhaled 440685
desain interior kamar tidur
20 Mar, 2012
You have noted very interesting points! ps nice web site.
hardwoodflooringcost.org
20 Mar, 2012
I think you did an awesome job explaining it. Sure beats having to research it on my own. Thanks 951805
Tarzan vibrator
20 Mar, 2012
If your real pals know you as your nickname, use that nickname as your 1st name online. When you 1st friend someone, focus on producing a private comment that weaves connection. 84555
a3118536
21 Mar, 2012
I’ve said that least 3118536 times. SCK was here
a1381225
21 Mar, 2012
I’ve said that least 1381225 times. SCK was here
physical therapy assistant
21 Mar, 2012
But wanna say that this really is invaluable , Thanks for taking your time to write this. 979785
Disruptive Innovation
22 Mar, 2012
Such a well written post.. Thnkx for sharing this post !! Also you can check my AV女優 !
orange county limo
22 Mar, 2012
Thanks For This Blog, was added to my bookmarks.
self esteem
22 Mar, 2012
What is blogspot when it comes to live streaming football?
militare-ordine-del-collare
22 Mar, 2012
I was reading some of your posts on this internet site and I think this internet site is really instructive! Continue putting up.
carpet cleaning radlett
22 Mar, 2012
Just what I was searching for, regards for posting .
Christian Louboutin Black patent leather knee-high boots
22 Mar, 2012
http://www.dochristianlouboutin.com/christian-louboutin-womens-sandals-c-1_11.html
louis vuitton wallets
22 Mar, 2012
I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!…
sandales femme
4 May, 2012
HURRAY! can
Freddie Mac
14 May, 2012
Hmm is anyone else encountering problems with the pictures on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.
Saturday Night Fever
17 May, 2012
Awesome blog! Do you have any hints for aspiring writers? I’m planning to start my own site soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely confused .. Any suggestions? Thank you!