aspose file tools*
The moose likes Beginning Java and the fly likes programatically compile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "programatically compile" Watch "programatically compile" New topic
Author

programatically compile

Amir Iqbal
Ranch Hand

Joined: Jun 23, 2007
Posts: 97
would any one please tell me that if i want to compile "abc.txt"(in which i have written simple java code) from my java programe(say TestClass) how can i do this??? if someone knows the code please do paste in reply......i am waiting for your response......

regards:
Amir Iqbal


i am Java +ve Now !
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42286
    
  64
Can you store the code in .java file on disk? If so, you can use the javac compiler internally, somewhat like this:



The first parameter is an array of absolute paths of Java source files, the second is where error messages should go, so you might use "new PrintWriter(System.err)" for it. It returns 0 if compilation worked fine, some other int if not.

If it all needs to be in memory then it gets a bit trickier. I described how it can work in this recent article.

Another approach would be to drive javac using Runtime.exec. Which method is best depends on what you intend to do with the resulting class.
[ November 10, 2007: Message edited by: Ulf Dittmer ]

Ping & DNS - my free Android networking tools app
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

You can also check out these examples from java2s.com. Please note that you have to run it from the java.exe from the JDK bin folder, otherwise you'll get a null Java Compiler object.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Amir Iqbal
Ranch Hand

Joined: Jun 23, 2007
Posts: 97
thanks alot my frndz Ulf and Rob and everyone who paid attention.
thank you very much.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14270
    
  21

Originally posted by Ulf Dittmer:
Can you store the code in .java file on disk? If so, you can use the javac compiler internally, somewhat like this:


Note that if you do this, you are using an internal Sun package, that you're not really supposed to use. See this: Why Developers Should Not Write Programs That Call 'sun' Packages.

Since Java 6, there is an official API to call the Java compiler from your program. It is in the package javax.tools. Lookup the API documentation for that package.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: programatically compile