获取jar包所在路径

该代码段是一个Java方法,用于从给定的类(Class)对象中获取JAR文件的父目录路径。首先,它从类的资源路径字符串中移除'file:/', 'jar!'和'%20'等不必要的部分。接着,如果路径不以'.jar'结尾(可能是在Spring Tools Suite中运行),则进一步处理路径。最后,使用Java 8的Paths类获取父目录并返回。
摘要由CSDN通过智能技术生成
private static String getParentDirectoryFromJar(Class aclass) {
        String dirtyPath = aclass.getResource("").toString();
        String jarPath = dirtyPath.replaceAll("^.*file:/", ""); //removes file:/ and everything before it
        jarPath = jarPath.replaceAll("jar!.*", "jar"); //removes everything after .jar, if .jar exists in dirtyPath
        jarPath = jarPath.replaceAll("%20", " "); //necessary if path has spaces within
        if (!jarPath.endsWith(".jar")) { // this is needed if you plan to run the app using Spring Tools Suit play button.
            jarPath = jarPath.replaceAll("/classes/.*", "/classes/");
        }
        String directoryPath = Paths.get(jarPath).getParent().toString(); //Paths - from java 8
        log.info("get jar path: " + directoryPath);
        return directoryPath;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值