这里实现一个小功能,仅用于记忆
功能:
- 解压一个jar包到本地一个目录
- 把一个目录压缩成一个jar包
/**
* 1,读取jar包,得到class文件
* 2,把class文件持久化到本地磁盘
* 3,组装class文件打成一个新jar包
* 4,新jar包提交到flink环境去执行任务
*/
public static void main(String[] args) throws Exception {
//解压jar文件到临时目录
List<String> classPathList = unzipJar("D:\\Downloads\\", "D:\\IDEA_PROJECT\\Custom_operator\\flink-test\\target\\flink-1.0.jar");
//重新压缩成jar包
zipJar("D:\\Downloads\\","test.jar","D:\\Downloads\\");
}
/**
* 将classPath路径下的所有文件,打成jar包。
* jar包的路径是${binJarPath}\${binJarName}.jar
*
* 主要还是里面工具包里面的jar命令部分的代码
* @param binJarPath 生成jar包的地址
* @param binJarName 生成jar包的名字
* @param classPath 所有的.class文件所在的路径
*/
public static void zipJar(String binJarPath, String binJarName, String classPath) throws Exception {
if (new File(classPath).exists()) {
Class clazz = Class.forName("sun.tools.jar.Main");
Constructor constructor = clazz.getConstructor(new Class[]{PrintStream.class, PrintStream.class, String.class});
Object object = constructor.newInstance(System.out, System.err, "jar");
Method method = clazz.getMethod("run", String[].class);
String[] args = new String[5];
args[0] = "-cvf";
args[1] = binJarPath + binJarName;
args[2] = "-C";
args[3] = classPath;
args[4] = ".";
method.invoke(object, new Object[]{args});
}
}
/**
* 解压缩jar文件
* @param destinationDir 要解压到的文件路径
* @param jarPath jar文件路径
* @return List<String> 类路径
* @throws IOException
*/
public static List<String> unzipJar(String destinationDir, String jarPath) throws IOException {
File file = new File(jarPath);
JarFile jar = new JarFile(file);
List<String> classPathList = new ArrayList<>();
for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) {
JarEntry entry = (JarEntry) enums.nextElement();
String fileName = destinationDir + File.separator + entry.getName();
File f = new File(fileName);
if (fileName.endsWith("/")) {
f.mkdirs();
}
classPathList.add(fileName);
}
for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) {
JarEntry entry = (JarEntry) enums.nextElement();
String fileName = destinationDir + File.separator + entry.getName();
File f = new File(fileName);
if (!fileName.endsWith("/")) {
InputStream is = jar.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(f);
while (is.available() > 0) {
fos.write(is.read());
}
fos.close();
is.close();
}
classPathList.add(fileName);
}
return classPathList.stream().filter(s->s.indexOf(".class")!=-1).collect(Collectors.toList());
}
标签:String,jar,目录,File,某个,new,fileName,class
From: https://www.cnblogs.com/fantongxue/p/17176458.html