Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java Compiler

843789Sep 19 2010 — edited Sep 20 2010
Hey everybody,

Well, I was trying to compile a piece of java code from within java program itself.

But, I am having some trouble with this example code which I am learning from:

Here is the code:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;

public class JVMComp {

    public static void main (String[] args) {
        String sourceFile = "c:/HelloWorld.Java";
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnostics =
            new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

        // prepare the source file(s) to compile
        List<File> sourceFileList = new ArrayList <File> ();
        sourceFileList.add (new File (sourceFile));
        Iterable<? extends JavaFileObject> compilationUnits =fileManager.getJavaFileObjectsFromFiles (sourceFileList);
        CompilationTask task = compiler.getTask (null,fileManager, null, null, null, compilationUnits);
        boolean result = task.call();
        if (result) {
            System.out.println ("Compilation was successful");
        } else {
            System.out.println ("Compilation failed");
        }
        try {
            fileManager.close ();
        } catch (IOException e) {
        }
    }
}
Its from [Original Article: Java2S: Java Compiler tools: how you can compile a Java source from inside a Java program|http://www.java2s.com/Code/Java/JDK-6/JavaCompilertoolshowyoucancompileaJavasourcefrominsideaJavaprogram.htm]

I made a few changes to it to accomodate for some errors. But can someone explain to me what is going on in this piece of code.

Just to make it clear, I do not own this code/ it is not mine and will take it out of this forum if required to do so.

Hopefully you all can help me out with this.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 18 2010
Added on Sep 19 2010
23 comments
745 views