javaargumentsjava-compiler-api

javax.tools.JavaCompiler "arguments" arg


So I've come across an annoying little issue between the api for javax.tools.JavaCompiler and the cmd line compiler (which are the same thing!). I simply want to use an argument to javac like: *-d C:\compiled\ C:\programs\HelloWorld.java *. This works great in cmd prompt, but my code is failing, saying that the file doesn't exist.

public class Test {

    private static String programsDir = "C:\\programs\\";
    private static String compiledDir = "C:\\compiled\\";
    private static String fileName = "HelloWorld.java";

    public static void main(String[] args){

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        String arguments = "-d " + compiledDir + " " + programsDir + fileName ;
        compiler.run(System.in, System.out, System.err, arguments);
    }

The output is:

javac: file not found: -d C:\compiled\ C:\programs\HelloWorld.java
Usage: javac <options> <source files>
use -help for a list of possible options

But I can cut and paste "-d C:\compiled\ C:\programs\HelloWorld.java" into javac. That is, javac -d C:\compiled\ C:programs\HelloWorld.java works.


Solution

  • run expects a list of args, have you tried:

    String[] args = {"-d", compiledDir, programsDir + fileName};
    compiler.run(System.in, System.out, System.err, args);