pony

抄袭是一种美德

获得jar包存放路径的方法

  在 java 中, System.getProperty("user.dir") 得到的是当前工作路径(对应命令行命令就是 linux 下的 pwd 、 windows 下的 cd ),而 System.getProperty("user.home") 得到的是当前用户主目录(对应于 linux 下的 ~ 目录、 windows 下的 document and settings\username );但如果你想得到所运行的 java 程序所在的路径,似乎并没有什么简单的方法。

  比如说,有一个 pathTest.jar 包放在 D:\zeal\webdev 下,这个 jar 执行的时候需要在当前目录下读写一个 test.log 文件。如果不采用绝对路径来读写 test.log 的话,不同的 jar 运行方式会带来不同的结果:

cd D:\zeal\webdev
java -jar pathTest.jar

( test.log 将生成在 D:\zeal\webdev 目录下 )

cd E:\sun\jre\bin
java -jar D:\zeal\webdev\pathTest.jar

( test.lgo 将生成在 E:\sun\jre\bin 目录下 )

  这势必造成潜在的运行错误。解决的方法是必须在程序中指定 test.log 文件的绝对路径。从本意上来讲,这里我们希望 test.log 与 pathTest.jar 位于相同的路径之下。但显然无论是 "user.dir" 还是 "user.home" 都不会返回正确的结果。

  幸好, java 允许我们定位某个 class 的 CodeSource , 通过 CodeSource 提供的 Location 信息就能够找到相关的文件路径。假设 pathTest.jar 的 main class 是 pathTest ,通过

new pathTest().getClass().getProtectionDomain().getCodeSource().getLocation();

  就可以得到 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"));
}

posted on 2008-09-18 15:40  马森  阅读(1344)  评论(0编辑  收藏  举报

导航