title: Programmatically compile java with JavaCompiler?
body: <p>I got this Java code from another Stack Overflow thread</p>
  
  <pre><code>import java.io.*;
  import javax.tools.JavaCompiler;
  import javax.tools.ToolProvider;
  
  public class Main {
    public static void main(String[] args) throws IOException{
      String source = " public class Test { public static void main(String args[]) {     System.out.println(\"hello\"); } }";
  
      // Save source in .java file.
      File root = new File("C:\\java\\");
      root.mkdir();
      File sourceFile = new File(root, "\\Test.java");
      Writer writer = new FileWriter(sourceFile);
      writer.write(source);
      writer.close();
  
      // Compile source file.
      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      compiler.run(null, null, null, sourceFile.getPath());
    }
  }
  </code></pre>
  
  <p>But I keep getting a NullPointerException like this</p>
  
  <pre><code>Exception in thread "main" java.lang.NullPointerException
      at com.zove.compiler.Main.main(Main.java:24)
  </code></pre>
  
  <p>It <em>does</em> compile but it throws the exception at runtime.
  What am I doing wrong?</p>