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

相关推荐
fouryears_234171 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~1 小时前
C#---StopWatch类
开发语言·c#
桦说编程3 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
lifallen3 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研3 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
没有bug.的程序员3 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋4 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
cui__OaO4 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
阿华的代码王国4 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Zyy~4 小时前
《设计模式》装饰模式
java·设计模式