java jar包存放位置_java取得某个jar包的位置

写程序的时候遇到这样一个问题,那就是:我想取的一个jar包的位置,这个很是费了一番心思,后来发现挺简单的。

java 允许我们定位某个 class 的

CodeSource , 通过 CodeSource 提供的 Location 信息就能够找到相关的文件路径。假设 pathTest.jar 的 main class 是 pathTest ,通过

就可以得到 pathTest.jar 的完整路径( file:/D:/zeal/webdev/pathTest.jar ),接下来怎么做就简单了。当然,实际应用中一般我们会选择把所有与jar相关的资源文件一起打包进去,或者使用 "user.home" 这样的固定位置来存放;除非在特殊情况下才会需要通过这个迂回的方式来获取相关的路径信息

private static String getPath(String name) {

//得到当前类加载器的路径

String currentPath = ExcelFilePath.class.getResource("/").toString();

currentPath = currentPath.substring(6); //去掉路径中的"file:/"

currentPath = URLDecoder.decode(currentPath);

//去掉WEB-INF/classes/

currentPath = currentPath.substring(0, currentPath.lastIndexOf("WEB-INF"));

//得到当前是什么操作系统

String os = System.getProperty("os.name");

String filePath = "";

if(os.startsWith("Windows"))

filePath = currentPath+PropertyManager.getProperty(name);

else

filePath = "/"+currentPath+PropertyManager.getProperty(name);

logger.info(filePath);

return filePath;

}

package cn.yicha.adclient.util;

import java.util.Properties;

import org.apache.log4j.Logger;

/**

* 获取邮件配置文件内容管理

* @author yicha

*

*/

public class PropertyManager {

private static Properties p = new Properties();

private static Logger logger = Logger.getLogger(PropertyManager.class);

public static String getProperty(String propName){

String propValue = null;

if(p.isEmpty()){

synchronized{

try {

p.load(PropertyManager.class.getResourceAsStream("/mail.properties"));

}catch (Exception e) {

logger.error("load mail properties file exception: "+e);

}

}

}

if(p!= null){

propValue = (String)p.get(propName);

if(propValue==null)propValue="";

}

return propValue;

}

public static void main(String [] pa){ System.out.println(PropertyManager.getProperty("ChargeMailContentFile")); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值