Search code examples
javapathprocessbuilder

How to get absolute file path located in class path when starting application (.jar file) from different directory?


Assume that Java application folder has these files:

app.jar
lib/file.exe

Inside app.jar I call .exe like this:

String[] exeCmd = new String[]{"lib/file.exe"};
ProcessBuilder pb = new ProcessBuilder(exeCmd);
...

If I start .jar file from the same directory - everything works fine. But if application is launched from different directory - lib/file.exe can't be found and ProcessBuilder quits with error "no such file or directory".

My question is - how to get right lib/file.exe path, and provide it to ProcessBuilder despite application is launched from other directories?

EDIT:

Now I'm thinking (different aproach) that those .exe like files I should put in user directory, like "Application Data" in Windows OS and later use them? It would be easy to find the path by calling System.getenv("APPDATA"); or System.getProperty("user.home"); in Unix. But on the other hand - if there are a lot of PC users - so those .exe files would be duplicated for each user (waste of disk space).


Solution

  • You can do it like this:

    YourClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();