Search code examples
javanullpointerexceptionjava-compiler-api

JavaCompiler giving NullPointerException on "ToolProvider.getSystemJavaCompiler()". I'm pretty sure I have JDK set up right?


The section of code in question is:

String fileToCompile = "C:/Users/Jeff/Documents/Test/Compiler 6/examplejavafile.java";//Absolute path
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
FileOutputStream errorStream = new FileOutputStream("Errors.txt");
int compilationResult = compiler.run(null, null, errorStream, "-verbose", fileToCompile);
if(compilationResult == 0){
    System.out.println("Compilation is successful");
}else{
    System.out.println("Compilation Failed");
}

When I run this section of code it gives me NPE on:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

Now I've been told that this is an error in the environment, but I have JDK installed and my CLASSPATH variable is set to "C:\Program Files\Java\jdk1.7.0_04\bin". I might be a noob and not understand how to run a program through JDK instead of JRE, but regardless I need help. (Also, I am using Eclipse, if it's any different.)


Solution

  • You need to import the ToolProvider since it is not defined, unless you just didn't include that information.

    import javax.tools.ToolProvider;