java 编译成jar_编译Java文件并生成jar包

/**

* 生成jar包

*/

private void createJAR(String sourcePath, String classPath, String outPath, String jarName) {

File classFile = new File(classPath);

BufferedInputStream in = null;

try {

if (!classFile.exists()) {

classFile.mkdirs();

}

File file = new File(sourcePath);

File[] listFiles = file.listFiles();

ArrayListlist = new ArrayList<>();

for (File file2 : listFiles) {

list.add(file2.getPath());

}

JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();

int result = -1;

for (int i = 0; list.size() > 0 && i < list.size(); i++) {

result = javaCompiler.run(null, null, null, "-d", classPath, list.get(i));

}

// 如果结果为0,说明编译成功, 可以打包

if (result == 0) {

compress(classPath, outPath + jarName);

}

} catch (Exception e) {

e.printStackTrace();

logger.error("生成jar包时出现了异常:" + e);

}

}

public void compress(String dir, String jarName) throws Exception {

File folderObject = new File(dir);

if (folderObject.exists()) {

List fileList = getSubFiles(new File(dir));

// 压缩文件名

Manifest manifest = new Manifest();

manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

FileOutputStream fos = new FileOutputStream(jarName);

JarOutputStream zos = new JarOutputStream(fos, manifest);

JarEntry ze = null;

byte[] buf = new byte[1024];

int readLen = 0;

for (int i = 0; i < fileList.size(); i++) {

File f = (File) fileList.get(i);

ze = new JarEntry(getAbsFileName(dir, f));

ze.setSize(f.length());

ze.setTime(f.lastModified());

zos.putNextEntry(ze);

InputStream is = new BufferedInputStream(new FileInputStream(f));

while ((readLen = is.read(buf, 0, 1024)) != -1) {

zos.write(buf, 0, readLen);

}

is.close();

}

zos.close();

} else {

throw new Exception("文件夹不存在!");

}

}

private List getSubFiles(File baseDir) {

List fileList = new ArrayList();

File[] tmp = baseDir.listFiles();

for (int i = 0; i < tmp.length; i++) {

if (tmp[i].isFile()) {

fileList.add(tmp[i]);

}

if (tmp[i].isDirectory()) {

fileList.addAll(getSubFiles(tmp[i]));

}

}

return fileList;

}

private String getAbsFileName(String baseDir, File realFileName) {

File real = realFileName;

File base = new File(baseDir);

String ret = real.getName();

while (true) {

real = real.getParentFile();

if (real == null)

break;

if (real.equals(base))

break;

else {

ret = real.getName() + "/" + ret;

}

}

return ret;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值