写程序的时候遇到这样一个问题,那就是:我想取的一个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"));
}