Java开发的可执行jar包中,常需要获取jar文件所在目录。比如访问同一目录下配置文件等
以下是本来摸索出的方法:
String root = System.class.getResource("/").getPath();
try {
return URLDecoder.decode(new File(root).getAbsolutePath(), "UTF-8");
} catch (UnsupportedEncodingException e) {
//...
}
其中
- System.class很重要,换成其他比如当前类的反射对象,拿到的path就不对;
- 返回getPath返回的字符串默认是URL编码的,(比如空格写作%20)所以需要使用URLDecoder