最开始我是用能够这种方式来获取当前 jar 包的文件的:
private static String LOCATION = [MainClass].class.getProtectionDomain()
.getCodeSource().getLocation().getFile();
但是如果路径中包含中文,就会变成带“%xx%xx”格式的字符串。所以应该这样写才对:
private static String LOCATION;
static {
try {
LOCATION = URLDecoder.decode([MainClass].class.getProtectionDomain()
.getCodeSource().getLocation().getFile(), “UTF-8″);
} catch (UnsupportedEncodingException e) {
LOCATION = “”;
}
}
对于Java程序,无论是未打包Class的还是打包的JAR都有效。
原文: http://blog.163.com/emily_fighting@126/blog/static/10652720720102235652416/
本文介绍了一种在Java中正确获取当前jar包或未打包类文件路径的方法,尤其关注于解决路径中包含中文字符的问题。

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



