88 lines
2.6 KiB
Java
88 lines
2.6 KiB
Java
package com.muyu.util;
|
||
|
||
import org.apache.logging.log4j.LogManager;
|
||
import org.apache.logging.log4j.Logger;
|
||
|
||
import javax.tools.*;
|
||
import java.io.File;
|
||
import java.io.IOException;
|
||
import java.io.OutputStreamWriter;
|
||
import java.io.PrintWriter;
|
||
import java.nio.charset.Charset;
|
||
import java.util.*;
|
||
|
||
public class SourceCodeCompiler {
|
||
|
||
private static final Logger log = LogManager.getLogger(SourceCodeCompiler.class.getName());
|
||
|
||
/**
|
||
* 获取系统java编译器
|
||
*/
|
||
private static JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
||
/**
|
||
* 获取java文件管理器
|
||
*/
|
||
private static StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
|
||
|
||
|
||
/**
|
||
* 输入编译的文件夹路径
|
||
* @param path 文件夹路径
|
||
*/
|
||
public static void javaCompilerPath(String path){
|
||
try {
|
||
List<File> files = JavaCodeScan.getJavaFiles(path);
|
||
System.out.println(files);
|
||
File[] array = files.toArray(new File[files.size()]);
|
||
javaCompiler(array);
|
||
}catch (Exception e){
|
||
log.error(e);
|
||
}
|
||
}
|
||
|
||
|
||
public static void javaCompilerFile(String... filePath){
|
||
int filePathLength = filePath.length;
|
||
File[] files = new File[filePathLength];
|
||
|
||
for (int i = 0; i < filePathLength; i++) {
|
||
files[i] = new File(filePath[i]);
|
||
}
|
||
javaCompiler(files);
|
||
}
|
||
|
||
|
||
/**
|
||
*可以同时编译多个java源代码
|
||
* @param file
|
||
*/
|
||
public static void javaCompiler(File...file){
|
||
try {
|
||
//通过源文件获取到想要编译的java类源代码迭代器,包括所有的内部类,其中每一个类都是一个JavaFileObjects,也被称为一个汇编单元
|
||
Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(file);
|
||
String[] strings = {"-classpath","home/","-verbose","-d", "home/"};
|
||
//生成编译任务
|
||
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, List.of(strings), null, javaFileObjects);
|
||
//执行编译任务
|
||
task.call();
|
||
}catch (Exception e){
|
||
log.error(e);
|
||
}
|
||
}
|
||
|
||
/**
|
||
*可以编译单个java源代码
|
||
* @param filePath
|
||
*/
|
||
public static void javaCompilerFile(String filePath){
|
||
try {
|
||
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
||
int results = compiler.run(null, null, null, filePath);
|
||
System.out.println((results == 0)?"编译成功":"编译失败");
|
||
}catch (Exception e){
|
||
log.error(e);
|
||
}
|
||
}
|
||
|
||
}
|