Java读写Jar

Java提供了读写jar的类库Java.util.jar,Java获取解析jar包的工具类如下:

java 复制代码
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

/**
 * jar包解析器
 *
 */
public class JarAnalyzer {

    /**
     * jar 文件路径
     */
    private String jarFilePath;

    /**
     * 构造函数
     *
     * @param jarFilePath 文件路径
     */
    public jarAnalyzer(String jarFilePath) {
        this.jarFilePath = jarFilePath;
    }

    /**
     * 获取jar包属性
     *
     * @return jar包所有属性
     * @throws IOException
     */
    public Map<String, String> getJarAttrs() throws IOException {
        URL url = new File(this.jarFilePath).toURI().toURL();
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});
        URL manifestUrl = urlClassLoader.findResource("META-INF/MANIFEST.MF");
        Manifest manifest = new Manifest(manifestUrl.openStream());
        Attributes mainAttributes = manifest.getMainAttributes();
        Map<String, String> attrs = new HashMap<>();
        mainAttributes.forEach((key, value) -> {
            attrs.put(String.valueOf(key), String.valueOf(value));
        });
        return attrs;
    }

    /**
     * 获取入口类全路径名
     *
     * @return 入口类全路径名
     * @throws IOException
     */
    public String getProgamClass() throws IOException {
        for (String key : getJarAttrs().keySet()) {
            if ("program-class".equals(key)) {
                return getJarAttrs().get(key);
            }
        }
        return null;
    }

    /**
     * 获取jar包所有类名
     *
     * @return jar包所有类名
     * @throws IOException
     */
    public Set<String> getAllClasses() throws IOException {
        File givenFile = new File(this.jarFilePath);
        Set<String> classNames = new HashSet<>();
        try (JarFile jarFile = new JarFile(givenFile)) {
            Enumeration<JarEntry> e = jarFile.entries();
            while (e.hasMoreElements()) {
                JarEntry jarEntry = e.nextElement();
                if (jarEntry.getName().endsWith(".class")) {
                    String className = jarEntry.getName()
                            .replace("/", ".")
                            .replace(".class", "");
                    classNames.add(className);
                }
            }
            return classNames;
        }
    }

}

测试类

java 复制代码
public static void main(String[] args) throws Exception {
        String jarPath = "/xxx/TopSpeedWindowing.jar";

        JarAnalyzer jarAnalyzer = new JarAnalyzer(jarPath);

        log.info("jar包所有属性:");
        jarAnalyzer.getJarAttrs().forEach((key, value) -> {
            log.info("key={},value={}", key, value);
        });

        log.info("MainClass -> {}", jarAnalyzer.getProgamClass());

        log.info("jar包含有的类:");
        jarAnalyzer.getAllClasses().forEach(clzz -> {
            log.info("className ->{}", clzz);
        });
    }

测试解析结果

参考文献:

https://stackoverflow.com/questions/1272648/reading-my-own-jars-manifest

https://www.baeldung.com/jar-file-get-class-names

相关推荐
某空_22 分钟前
【Android】使用ViewPager2实现简单的轮播图
java
武子康23 分钟前
Java-145 深入浅出 MongoDB 基本操作详解:数据库查看、切换、创建集合与删除完整教程
java·数据库·sql·mysql·mongodb·性能优化·系统架构
white-persist31 分钟前
XXE 注入漏洞全解析:从原理到实战
开发语言·前端·网络·安全·web安全·网络安全·信息可视化
练习时长一年1 小时前
Spring内置功能
java·前端·spring
铉铉这波能秀1 小时前
如何在Android Studio中使用Gemini进行AI Coding
android·java·人工智能·ai·kotlin·app·android studio
_Yoke1 小时前
Java 枚举多态在系统中的实战演进:从枚举策略到自动注册
java·springboot·策略模式
人生导师yxc1 小时前
Java中Mock的写法
java·开发语言
半路程序员1 小时前
Go语言学习(四)
开发语言·学习·golang
青岛少儿编程-王老师1 小时前
CCF编程能力等级认证GESP—C++5级—20250927
java·数据结构·c++
毕设源码-郭学长1 小时前
【开题答辩全过程】以 办公管理系统为例,包含答辩的问题和答案
java·eclipse