Rommel Rico: Random ramblings

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.

  • 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

  • its not giving swing result what can i do?

  • I’m not talking about swing.

  • 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!!

  • it works perfectly.
    Do you know how i can compile, and then run on a separate Java virtual machine?

  • Very interesting info !Perfect just what I was searching for! “We are shaped and fashioned by what we love.” by Johann von Goethe.

  • 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.

  • 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.

  • I genuinely enjoy examining on this site, it holds wonderful blog posts.

  • 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

  • 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

  • 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.

  • 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!

  • 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

  • You have noted very interesting points! ps nice web site.

  • I think you did an awesome job explaining it. Sure beats having to research it on my own. Thanks 951805

  • 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

  • I’ve said that least 3118536 times. SCK was here

  • I’ve said that least 1381225 times. SCK was here

  • But wanna say that this really is invaluable , Thanks for taking your time to write this. 979785

  • Such a well written post.. Thnkx for sharing this post !! Also you can check my AV女優 !

  • Thanks For This Blog, was added to my bookmarks.

  • What is blogspot when it comes to live streaming football?

  • I was reading some of your posts on this internet site and I think this internet site is really instructive! Continue putting up.

  • Just what I was searching for, regards for posting .

  • 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!…

  • HURRAY! can

  • 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.

  • 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!

You can follow any responses to this entry through the RSS 2.0 feed.