对于常规java class打成jar文件后,要获取它的本地路径,可以用如下方法。

final File f = new File(TestClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
System.out.println(f.getAbsolutePath());

 

如果是SpringBoot的启动类,它会被SpringBoot的class loader加载,实际启动jar的时候其实启动的是spring class loader,这个时候如果还想获取jar的本地路径,可以先获取它的loader,再用同样的方法获取路径:

final File f = new File(TestClass.class.getClassLoader().getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
System.out.println(f.getAbsolutePath());

 

相关文章:

  • 2021-08-25
  • 2022-12-23
  • 2022-01-29
  • 2021-12-20
  • 2022-12-23
  • 2022-12-23
  • 2022-01-03
  • 2022-01-07
猜你喜欢
  • 2022-12-23
  • 2021-11-01
  • 2021-10-27
  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
  • 2021-07-25
相关资源
相似解决方案