1.将指定目录下的java文件编译为class文件
import org.apache.commons.lang3.StringUtils;
import javax.tools.*;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class CompilerUtil {
private static JavaCompiler javaCompiler = null;
private static String UTF = "UTF-8";
private CompilerUtil(){
}
private static JavaCompiler getJavaCompiler(){
if (javaCompiler == null) {
synchronized (CompilerUtil.class){
if (javaCompiler == null) {
javaCompiler = ToolProvider.getSystemJavaCompiler();
}
}
}
return javaCompiler;
}
public static void compiler( String filePath, String targetDir, String sourceDir,String encoding, String jarPath)
throws Exception {
List<File> sourceFileList = File4ComplierUtils.getSourceFiles(filePath);
if (sourceFileList.size() == 0) {
System.out.println(filePath + "目录下查找不到任何java文件");
return;
}
String jars = File4ComplierUtils.getJarFiles(jarPath);
if(StringUtils.isBlank(jars)){
jars="";
}
File targetFile = new File(targetDir);
if(!targetFile.exists())targetFile.mkdirs();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = getJavaCompiler().getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFileList);
Iterable<String> options = Arrays.asList("-encoding",encoding,"-classpath",jars,"-d", targetDir, "-sourcepath", sourceDir);
JavaCompiler.CompilationTask task = getJavaCompiler().getTask(
null,
fileManager,
diagnostics,
options,
null,
compilationUnits);
boolean success = task.call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics())
System.out.printf(
"Code: %s%n" +
"Kind: %s%n" +
"Position: %s%n" +
"Start Position: %s%n" +
"End Position: %s%n" +
"Source: %s%n" +
"Message: %s%n",
diagnostic.getCode(), diagnostic.getKind(),
diagnostic.getPosition(), diagnostic.getStartPosition(),
diagnostic.getEndPosition(), diagnostic.getSource(),
diagnostic.getMessage(null));
fileManager.close();
System.out.println((success)?"编译成功":"编译失败");
}
}
2.将指定目录下的class文件打入到jar包中
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
public class CreateJarUtils {
public static void createTempJar(String rootPath, String targetPath, String jarFileName) throws IOException {
if (!new File(rootPath).exists()) {
throw new IOException(String.format("%s路径不存在", rootPath));
}
if (StringUtils.isBlank(jarFileName)) {
throw new NullPointerException("jarFileName为空");
}
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
File jarFile = File.createTempFile("edwin-", ".jar", new File(System.getProperty("java.io.tmpdir")));
JarOutputStream out = new JarOutputStream(new FileOutputStream(jarFile), manifest);
createTempJarInner(out, new File(rootPath), "");
out.flush();
out.close();
File targetFile = new File(targetPath);
if (!targetFile.exists()) targetFile.mkdirs();
File targetJarFile = new File(targetPath + File.separator + jarFileName + ".jar");
if(targetJarFile.exists() && targetJarFile.isFile())targetJarFile.delete();
FileUtils.moveFile(jarFile, targetJarFile);
}
private static void createTempJarInner(JarOutputStream out, File f,
String base) throws IOException {
if (f.isDirectory()) {
File[] fl = f.listFiles();
if (base.length() > 0) {
base = base + "/";
}
for (int i = 0; i < fl.length; i++) {
createTempJarInner(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new JarEntry(base));
FileInputStream in = new FileInputStream(f);
byte[] buffer = new byte[1024];
int n = in.read(buffer);
while (n != -1) {
out.write(buffer, 0, n);
n = in.read(buffer);
}
in.close();
}
}
}
3.先生成class在生成jar的工具类,对外使用
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class BuildJarUtil {
static String basePath = "x:\\xxxx\\xxxx\\xxxx";
static String jarFilePath = "x:\\xxxx\\xxxx\\xxxx";
static String[] srcFiles = {
"/xxxx/xxxx/"
};
static String jarReyOnPath = "x:\\xxxx\\xxxx\\lib";
static String jarFileName = "xxxx";
static String encoding = "utf-8";
public static void main(String[] args) {
String sourcePath = "";
String classPath = "";
try {
System.out.println("分隔符:" + File.separator);
System.out.println("资源拷贝......");
sourcePath = jarFilePath + File.separator + "source";
copySource(sourcePath);
System.out.println("资源拷贝结束");
System.out.println("编译资源......");
classPath = jarFilePath + File.separator + "class";
try {
CompilerUtil.compiler(sourcePath, classPath, basePath, encoding, jarReyOnPath);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("编译资源结束");
System.out.println("生成jar......");
CreateJarUtils.createTempJar(classPath, jarFilePath, jarFileName);
System.out.println("生成jar完成");
ExeSuccess(sourcePath, classPath);
} catch (IOException e) {
e.printStackTrace();
deleteTempFile(sourcePath, classPath);
} finally {
}
}
private static void ExeSuccess(String sourcePath, String classPath) {
final String sourcedir = sourcePath;
final String classdir = classPath;
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
deleteTempFile(sourcedir, classdir);
System.out.println("***************执行完毕**********************");
}
});
}
private static void deleteTempFile(String sourcePath, String classPath) {
try {
File sourceFile = new File(sourcePath);
if (sourceFile.exists()) {
FileUtils.deleteDirectory(sourceFile);
}
File classFile = new File(classPath);
if (classFile.exists()) {
FileUtils.deleteDirectory(classFile);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void copySource(String sourcePath) throws IOException {
for (String f : srcFiles) {
String path = f.replace("/", File.separator);
System.out.println(path);
File srcFile = new File(basePath + path);
File targetFile = new File(sourcePath + path);
FileUtils.copyDirectory(srcFile, targetFile, new FileFilter() {
@Override
public boolean accept(File pathname) {
System.out.println(pathname);
return pathname.getName().endsWith(".java");
}
});
}
}
}
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class File4ComplierUtils {
public static List<File> getSourceFiles(String sourceFilePath){
List<File> sourceFileList = new ArrayList<File>();
try {
getSourceFiles(new File(sourceFilePath),sourceFileList);
} catch (Exception e) {
e.printStackTrace();
sourceFileList = null;
}
return sourceFileList;
}
public static String getJarFiles(String sourceFilePath){
String jars = "";
try {
getJarFiles(new File(sourceFilePath),jars);
} catch (Exception e) {
e.printStackTrace();
jars = "";
}
return jars;
}
private static void getSourceFiles(File sourceFile, List<File> sourceFileList) throws Exception {
if (!sourceFile.exists()) {
throw new IOException(String.format("%s目录不存在",sourceFile.getPath()));
}
if (null == sourceFileList) {
throw new NullPointerException("参数异常");
}
if (sourceFile.isDirectory()) {
File[] childrenDirectoryFiles = sourceFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File file : sourceFile.listFiles()) {
if(file.isDirectory()){
getSourceFiles(file,sourceFileList);
} else {
sourceFileList.add(file);
}
}
}else{
sourceFileList.add(sourceFile);
}
}
private static String getJarFiles(File sourceFile,String jars) throws Exception {
if (!sourceFile.exists()) {
throw new IOException("jar目录不存在");
}
if (!sourceFile.isDirectory()) {
throw new IOException("jar路径不为目录");
}
if(sourceFile.isDirectory()){
for (File file : sourceFile.listFiles()) {
if(file.isDirectory()){
getJarFiles(file,jars);
}else {
jars = jars + file.getPath() + ";";
}
}
}else{
jars = jars + sourceFile.getPath() + ";";
}
return jars;
}
}