0

I am working on a Spring Boot application runned as executable jar. In my code I am trying to retrieve the folder where is located the runned jar file. But I am finding some difficulties. I have done in this way:

File jarFile = new File(BeanConfig.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String jarFolder = jarFile.getParentFile().getPath();
System.out.println("FOLDER: " + jarFolder);

The problem is that, doing in this way, the printed output is something like this:

FOLDER: file:/home/andrea/git/notartel-api-batch/target/UpdateInfoBatch-0.0.1-SNAPSHOT.jar!/BOOT-INF

And this is not what I need because I need the path of the directory containing my jar file that int this case is this one: /home/andrea/git/notartel-api-batch/target/

What is wrong? What am I missing? How can I try to fix this behavior in order to retrieve the path of the directory containing my jar file?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • You can find the answer here https://stackoverflow.com/questions/46657181/how-to-get-spring-boot-application-jar-parent-folder-path-dynamically – John Sep 07 '21 at 14:14

2 Answers2

1

In a Spring Boot application you can do this:

ApplicationHome applicationHome = new ApplicationHome(MySpringBootApp.class);
String jarFolder = applicationHome.getDir().getAbsolutePath();
System.out.println("FOLDER: " + jarFolder);
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
0
ApplicationHome home = new ApplicationHome(MyMainSpringBootApplication.class);
home.getDir();    // returns the folder where the jar is.
home.getSource(); // returns the jar absolute path.
John
  • 258
  • 1
  • 5
  • 21