How to Compile Java Source within Java Program
By Angsuman Chakraborty, Gaea News NetworkThursday, March 26, 2009
This small trick will tell you how you can compile a java source file from another java file on the go. You do not need to run it on a different page and compile it there and then get back to this program. This will be immensely helpful for a program that has some dynamic segments of codes which need to be compiled here within. Basically what we are gonna do is we will use getSystemJavaCompiler() method in the ToolProvider class that returns an object of some class that implements JavaCompiler.
1. The implementation needs tools.jar file usually available in the <JDK60_INSTALLATION_DIR>libtools.jar. So you need to give the proper directory path in the class path so that we can use import javax.tools.*
Or you can use
cp /usr/java/jdk<version>/lib/tools.jar /usr/java/jdk<installation directory>/jre/lib/ext/
this command above to change it from terminal.
2. Now to compile that program from within another Java file, here is the code snippet you need to use
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler.run(null, null, null, fileName + “.java”) != 0) {
// Error message
}
And you are done.
Tags: compile java program, compile java source within java program, java program, run java program from another java
March 30, 2010: 4:17 am
I want to compile a java program ,location of which is C:\ass\Test.java..Can I compile the program from other drives such as D:\ or E:\ or from any other location like D:\surachit\aal\sd |
anil kanhangad |
February 15, 2010: 11:46 pm
i am able to run first java command succesfully (javac0.but not able to run the second one(ie java)..what is the peroblem? |
Saket |
Surachit