一、前言
关于flink源码包中org.apache.flink.runtime.util.JarFileCreator自定义Jar文件生成器,可以对指定路径outputFile文件,并追加.class打包生成.jar文件。
二、源码说明
package org.apache.flink.runtime.util;@b@@b@import java.io.File;@b@import java.io.FileOutputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.util.HashSet;@b@import java.util.Iterator;@b@import java.util.Set;@b@import java.util.jar.JarEntry;@b@import java.util.jar.JarOutputStream;@b@import java.util.jar.Manifest;@b@@b@public class JarFileCreator@b@{@b@ private static final String CLASS_EXTENSION = ".class";@b@ private final Set<Class<?>> classSet = new HashSet();@b@ private final File outputFile;@b@@b@ public JarFileCreator(File outputFile)@b@ {@b@ this.outputFile = outputFile;@b@ }@b@@b@ public synchronized void addClass(Class<?> clazz)@b@ {@b@ this.classSet.add(clazz);@b@ }@b@@b@ public synchronized void createJarFile()@b@ throws IOException@b@ {@b@ byte[] buf = new byte[128];@b@@b@ if (this.outputFile == null) {@b@ throw new IOException("Output file is null");@b@ }@b@@b@ if (this.outputFile.exists()) {@b@ this.outputFile.delete();@b@ }@b@@b@ JarOutputStream jos = new JarOutputStream(new FileOutputStream(this.outputFile), new Manifest());@b@ Iterator it = this.classSet.iterator();@b@ while (it.hasNext())@b@ {@b@ Class clazz = (Class)it.next();@b@ String entry = clazz.getName().replace('.', '/') + ".class";@b@@b@ jos.putNextEntry(new JarEntry(entry));@b@@b@ InputStream classInputStream = clazz.getResourceAsStream(clazz.getSimpleName() + ".class");@b@@b@ int num = classInputStream.read(buf);@b@ while (num != -1) {@b@ jos.write(buf, 0, num);@b@ num = classInputStream.read(buf);@b@ }@b@@b@ classInputStream.close();@b@ jos.closeEntry();@b@ }@b@@b@ jos.close();@b@ }@b@}