Tuesday, January 30, 2007

Running Javac from Java !

Oh Long time, No post .. So I decided to go for one :). I suspended the thread of JVM Part-N because some of my friends told that these things are also written in book, write something extra. For writing extra, I don't have knowledge :D

Anyway, as we all know Scripting language is the most powerful language for running real application and most of the time I get it challenging to convert that script code into Java code, but believe me I am always ready to take this challenge. So this time my challenge was to run set of Java codes from a single Java Program. In general we run java code by opening cmd and doing those javac,java.

Again, its a damn easy job for a scripting language, but ... Ah come on you are a java programmer. And here the result, though currently I am running one Java code only from other Java Program (sorry for writing the code in a bad way)

import java.io.*;

class JavaCode {
public static void main(String[] args1)
com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
File file = new File("V.java");
String filename = file.getName();
String classname = filename.substring(0, filename.length()-5);
String[] args = new String[] { filename };
int status = javac.compile(args);

(Some bad naming convention, some crap hard coding.. but you can pardon me for that :D ). Some unused part of code like taking classname, I am going to use it further to run the code. Ok this code is compiling and telling the status of V.java ...some Helloworld code (please put both in same location :) )

Ok so next is to run and print Hello World ... Not a tough job :)


anand said...

this coding is not running in java plz show me complete program

Vaibhav said...

jdk 1.6 you need !