获取当前JAR包的完整路径

获取资源文件或配置文件时,需要路径。

  1. public class JarUtils {
  2. /**
  3. * 获取class所在的Jar包的绝对地址(如果当前不为jar包,则返回的地址为class所在的module的绝对地址)
  4. * @return
  5. */
  6. public static String getLocalPath(Class clazz,String chartsName){
  7. String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
  8. if (chartsName == null||chartsName.isEmpty()){
  9. chartsName = "UTF-8";
  10. }
  11. try {
  12. return URLDecoder.decode(path,chartsName);
  13. //如果地址中存在中文的话,会出现乱码,所以需要处理一些编码格式
  14. } catch (UnsupportedEncodingException e) {
  15. e.printStackTrace();
  16. }
  17. return path;
  18. }
  19. }

如果为IDEA中运行,则获得编译后的class所在的文件夹:

/E:/tool/TestPath/out/production/TestPath/

如果为jar包运行,则获取jar包的地址,如图:

/E:/tool/TestPath/out/artifacts/TestPath_jar/TestPath.jar

image.png

获取执行程序的工作路径

  1. String path = System.getProperty("user.dir");

如果为IDEA中,运行,则获得该项目的地址:

E:\tool\TestPath

如果为jar,获得执行该jar的地址,如图:
image.png
获取到执行java -jar 命令的文件夹地址,而不是jar包所在的文件夹