Java获取 jar 中的所有类与包

本文介绍了如何在Java中通过JarFile类获取jar文件的内容,包括遍历jar中的所有条目并打印其路径和文件名。同时,提到在IDE执行可能需要打包为jar才能观察效果,涉及路径获取策略的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 获取当前项目路径, Main是当前类, 可以指定其它类, 这个无所谓
String pathname = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("当前路径: " + pathname);
// 使用JarFile打开jar文件
JarFile jar = null;
try {
    jar = new JarFile(pathname);

    Enumeration<JarEntry> entryEnumeration = jar.entries();
    while (entryEnumeration.hasMoreElements()) {
        // 获取JarEntry对象
        JarEntry entry = entryEnumeration.nextElement();
        // 获取当前JarEntry对象的路径+文件名
        System.out.println(entry.getName());
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        // 关闭jar文件
        jar.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

项目结构

 

结果

当前路径: /C:/Users/18528/Desktop/rjar.jar
META-INF/MANIFEST.MF
META-INF/
a/
a/A.class
a/b/
a/b/B.class
a/b/c/
a/b/c/C.class
Main.class

直接在IDE执行是看不到效果的,需要打包为jar。可以判断当前是否为jar,如果是则采用此方法,否则也通过 Main.class.getProtectionDomain().getCodeSource().getLocation().getPath() 获取当前项目路径去遍历目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值