获取当前JAR包的完整路径
获取资源文件或配置文件时,需要路径。
public class JarUtils {
/**
* 获取class所在的Jar包的绝对地址(如果当前不为jar包,则返回的地址为class所在的module的绝对地址)
* @return
*/
public static String getLocalPath(Class clazz,String chartsName){
String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
if (chartsName == null||chartsName.isEmpty()){
chartsName = "UTF-8";
}
try {
return URLDecoder.decode(path,chartsName);
//如果地址中存在中文的话,会出现乱码,所以需要处理一些编码格式
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return path;
}
}
如果为IDEA中运行,则获得编译后的class所在的文件夹:
/E:/tool/TestPath/out/production/TestPath/
如果为jar包运行,则获取jar包的地址,如图:
/E:/tool/TestPath/out/artifacts/TestPath_jar/TestPath.jar
获取执行程序的工作路径
String path = System.getProperty("user.dir");
如果为IDEA中,运行,则获得该项目的地址:
E:\tool\TestPath
如果为jar,获得执行该jar的地址,如图:
获取到执行java -jar 命令的文件夹地址,而不是jar包所在的文件夹