Starting with the 1.6 version of the JDK, the JDK provides a standard package that makes it easy to invoke the JVM's compiler, which makes it easy to compile Java source files using the JVM's compiler. The calling interface provided by the JDK is the Javacompiler class, which is in the JDK's Tools.jar package.
1. Using the Javacompiler interface to implement Java file compilation
String Soutputpath = "d:\\classes"; list<string> paths = new arraylist<string> ();p aths.add ("D:\\java\\test1.java");p aths.add ("D:\\java\\ Test2.java ");p aths.add (" D:\\java\\test3.java ");p aths.add (" D:\\java\\test4.java ");p aths.add (" d:\\java\\ Test5.java ");p aths.add (" D:\\java\\test6.java "); Javacompiler compiler = Toolprovider.getsystemjavacompiler ();D iagnosticcollector<javafileobject> Diagnostics = new Diagnosticcollector<javafileobject> (); Standardjavafilemanager FileManager = Compiler.getstandardfilemanager (diagnostics, NULL, NULL); Location olocation = standardlocation.class_output;filemanager.setlocation (Olocation,arrays.aslist (new File[] {new File (Soutputpath)}); iterable<? Extends javafileobject> compilationunits = filemanager.getjavafileobjectsfromstrings (paths); Javacompiler.compilationtask task = Compiler.gettask (null, filemanager,diagnostics, NULL, NULL, compilationunits); Boolean result = Task.call (); Filemanager.close ();
2. As mentioned earlier, Tools.jar is a package provided by the JDK, and when running an instance in the IDE, because the IDE's general configuration of the JRE is a separate JRE, you get javacompiler when you get the compiler that is provided by the JVM (get method: Javacompiler compiler = Toolprovider.getsystemjavacompiler ();), so NullPointerException is reported. The workaround is to modify the IDE's JRE path, modify it to the JRE path in the JDK, windows->preferences->java->installed JREs Select the JRE in the right-hand table, and edit the JRE path to %java_home%/jre the path so that the null pointer exception is not reported again when running.
Compiling Java source files using Javacompiler