Search code examples
javaclassloaderapache-commons-jci

How to compile java class with jci?


somebody I use this:

org.apache.commons.jci.compilers.JavacJavaCompiler

I have a jci class:

public void compile() {
    sourceDir = new File("java");
    sources = new String[] { "test/HelloWorld.java" };
    target = new File("result");

    JavacJavaCompilerSettings settings = new JavacJavaCompilerSettings();

    JavacJavaCompiler javacJavaCompiler = new JavacJavaCompiler(settings);

    System.out.println("compile -> " + sources);
    System.out.println("compile -> " + sourceDir);
    System.out.println("compile -> " + target);

    CompilationResult result = javacJavaCompiler.compile(sources,
            new FileResourceReader(sourceDir),
            new FileResourceStore(target));

    for (CompilationProblem cp : result.getErrors()) {
        System.out.println("compile -> " + cp.getStartLine());
        System.out.println("compile -> " + cp.getMessage());
    }
}

and my output is:

 compile -> 0
 compile -> Failure executing javac, but could not parse the error: javac: file not found:     test/HelloWorld.java
 Usage: javac <options> <source files>
 use -help for a list of possible options

some idea, ty.


Solution

  • The output is telling you clearly that the compiler cannot find your source file with the pathname that you have supplied. Two possible causes spring to mind:

    • you've supplied the wrong source file pathname, or
    • the JVM's "current directory" not the directory that contains the "test" directory used in the source pathname.

    Things to try:

    • Use an absolute pathname for the source file, just to prove that you can run the compiler.
    • Print out the value of System.getProperty("user.dir") ... which should match the JVM's current directory. Based on that, figure out what the relative pathname of the source file should be.