最近在使用eclipse的Export功能将一个工程打包成jar后,是引用JSmooth封装成了exe文件。
发现原来写的得到类的绝对路径的方法会出错。
即使将这个exe程序放在D盘运行,也可能会得到类似:
C:/Documents%20and%20Settings/cuilichen/Local%20Settings/Temp....
的路径。显然,这不是我们需要的。
其原因是程序在执行时,首先将jar包放到了C盘的临时文件夹下,
因此得到的路径是这样的。
看来需要找到新的方法。
原始方法是:
public String getPath() {
String strClassName = getClass().getName();
String strClassFileName = strClassName.substring(strClassName.lastIndexOf(".") + 1, strClassName.length());
URL url = getClass().getResource(strClassFileName + ".class");
String strURL = url.toString();
strURL = strURL.substring(strURL.indexOf("/") + 1);
return strURL;
}
这里采用的新方式是:
public String getPath2() throws Exception {
String strClassName = getClass().getName();
String strClassFileName = strClassName.substring(strClassName.lastIndexOf(".") + 1, strClassName.length());
File file = new File(strClassFileName + ".class");
return file.getCanonicalPath();
}
这样就可以得到正确的路径了。
本文探讨了在Eclipse中使用Export功能将工程打包成JAR并转换为EXE后,原有获取类绝对路径方法失效的问题,并提供了一种新的解决方案。

被折叠的 条评论
为什么被折叠?



