我从另一个Stack Overflow线程获得了这个Java代码
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());
}
}
Run Code Online (Sandbox Code Playgroud)
但我一直得到像这样的NullPointerException
Exception in thread "main" …Run Code Online (Sandbox Code Playgroud)