How to get the absolute path of the executed jar? - java

How do I get the location of the executed jar? I found a lot of solutions but none of them work for me. When I run them in my IDE everything is fine. As soon as I build a jar file and run it with java -jar myapp.jar the output is like /.../myapp.jar!/foo/bar
I will run the code in myapp.jar - not in any library.
Location of jar: /home/me/dev/myapp/myapp.jar
Expected output: /home/me/dev/myapp/
I don't want the working directory as I would get with System.getProperty("user.dir");
Why I want to do this:
I want to store and load a file beside the actual jar. Like
/home/me/bin/myapp/myapp.jar
/home/me/bin/myapp/license.key
I want to avoid storing the file into some generic folder like System.getProperty("user.home");. And I don't want to store the file within the jar file.

java.nio.file.Paths.get(".").toAbsolutePath() will return absolute path to current directory.

I use something along these lines:
[YourClass].class.getProtectionDomain().getCodeSource().getLocation().getPath()
Regards

Related

Get project directory from java classes

I have a problem with System.getProperty("user.dir") giving different directory when run by IDE and when I manually compile & run it in cmd. My thing is this, I have project structure like this:
project
- exports
- src
- main
- java
- Main
- file1
- file2
One of the args in main method is the name of one of those 2 files, that I then access.
When I configure my run in IDE it works like a charm - the directory I get is C:\Users\**\**\**\project and it is able to read and write to the file.
But when I compile it in cmd javac Main.java and then run it, I get C:\Users\**\**\**\project\src\main\java and because of that, I am unable to access the file without having to modify the path.
My question is, is there like a golden way, that would work for both these cases, without me having to alter the returned path?
EDIT:
For clear understanding, I know what System.getProperty("user.dir") returns, but my question was, if it is possible to get the same result somehow with using Path or if I have to get the path and edit it, so that it will end in project directory?
in IDE I get: C:\Users\petri\Desktop\CZM\bicycle-statistics
in cmd: C:\Users\petri\Desktop\CZM\bicycle-statistics\src\main\java
I want to get the same path in cmd, that I got in IDE.
I tried using Paths.get("").toAbsolutePath(), but it is the same thing.
So, what I did is this:
Path path = Paths.get("").toAbsolutePath();
while (!path.endsWith("project")) {
path = path.getParent();
}
And it works, but I am trying to ask, if there is some more elegant way, because I will have to defend my solution in front of my supervisor.
Normally your IDE will build source files in src/main/java and write the class files out to some other directory, like target/classes.
If your IDE built the project that way, then you can run it from the command line by switching to your project directory (cd C:\Users\**\**\**\project using your example) and then running:
java -classpath target/classes Main
assuming that target/classes is where your IDE put the files. If you really do have the class files in the source directory, then use -classpath src/main/java.
If you always run the program from the project directory, then you can assume within the program that the current directory is the project directory. You don't even have to use user.dir then, just use relative path names for everything, e.g., path/to/whatever.dat will automatically resolve to C:\Users\**\**\**\project\path\to\whatever.dat.
One of the args in main method is the name of one of those 2 files
Then make sure you enter the name correctly.
E.g. if the current working directory is the project folder, then name file1 will refer to the file1 file. If the current working directory is the java folder, then the argument to the program needs to be ..\..\..\file1.
That is because you give relative file names, which means they are relative to the current working directory.
Alternatively, give a fully qualified name, then the argument will be the same, regardless of what the current working directory is:
C:\Users\**\**\**\project\file1

How to access outside file from java jar

I have a jar that is reading a file using below code:
Thread.currentThread().getContextClassLoader().getResource(fileName);
I want to run this jar using java -jar .jar command but I want to keep this file outside my jar, so that I can edit the jar file later on without touching the jar. Can anyone help me, how to run this jar so that it will pick up the file from outside.
There are multiple approaches you can do that and it will depend on where would you like to place this external file. For the sake of this answer, I will refer to this file as config file
Not In The Same Directory
The first approach is where you will need to place this file outside the JAR and not necessarily next to the JAR file in the same directory. In that case, you can pass the file location of the config file using either an environment variable (if you are running the JAR in a shell for example) or a Java property.
To use an environment variable, assuming you are using some Linux distro, then you can use the export command to set the value; something like this:
$ export CONFIG_FILE_LOC=/etc/myapp/config.file
You can then read the value in your code using the System class by using the following code:
String fileLocationEnv = System.getenv("CONFIG_FILE_LOC");
Alternatively, you can set this as a property by adding the following segment to your launch command:
$ java -Dconfig.file.location=/etc/myapp/config.file -jar myapp.jar
You can then read the value in your code using the System class for properties using the following code:
String fileLocationProp = System.getProperty("config.file.location");
In The Same Directory
If you need the config file to co-exist in the same directory as your JAR file, then you can use the following code to get the JAR directory and then append the filename to it. Here's the code (assuming a class named MyApp)
try{
new File(MyApp.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch(URISyntaxException exception){
System.out.println("Exception");
}
Hope that helps.
To open the file as a resoure, add the folder containing the file(s) you want to use, to your classpath:
java -classpath .;config -jar myjar.jar
This example adds the current directory and the config directory to your classpath.
Multiple folders can be specified by using a separator. On windows use ';' , on unix use ':' .
To open the file as a File, you can just use
new File("configfile")
which will look in the working directory (directory where you launched your java)

How can I dynamically use externalized properties file with Spring jar?

With this setup (from Eclipse using Windows10)
I was able to correctly start my SpringBoot application. This one worked too (same directory pattern):
Now I'm packaging my project as JAR and I want to use an external properties file. I had an teste32.yml file beside my JAR at the same directory (also tried to use it inside /config directory, as show here, but it didn't work either)
I want to dynamically use a properties file beside my JAR file everytime. Doesn't matter at which directory they are, I wanted to dynamically point to a properties file always at the same directory as the JAR is. I want to say to my client: "take this JAR and this file, put them wherever you want and run this command X and everything will be alright". I'm trying to discover command X but before I add some dynamic path, I'm trying with absolutes paths. I'm using this:
java -jar myJar.jar -Dspring.config.name=teste32 -Dspring.config.location=C:\workspace\myProject\target\
I manually copied teste32 inside target\ to test this. But this didn't work. This didn't work either (only spring.config.location variants):
-Dspring.config.location=file:C:\workspace\myProject\target\
-Dspring.config.location=classpath:/
-Dspring.config.location=file:C:/workspace/myProject/target/
I also tried with no spring.config.location, only name
So my questions are:
What does classpath: and file: mean? Until now I got the 2 correct setups by pure luck and I would like to understand when to use them.
When I have my project package as a JAR, what classpath becomes?
Finally, which combination is necessary to dynamically use a properties always at the same directory as the JAR?
UPDATE
Using --debug at the correct example got me this line at the very begging (Spring banner was still visible):
2018-09-25 15:45:14.480 DEBUG 11360 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'file:src/main/resources/xirulei/teste32.yml' (file:src/main/resources/xirulei/teste32.yml)
But after moving myJar.jar and teste32.yml to a specific directory and running java -jar myJar.jar -Dspring.config.name=teste32 --debug (without spring.config.location, since teste32 is at the same directory as JAR), I simply didn't get any ConfigFileApplicationListener debug line.
a) java -jar myJar.jar -Dspring.config.name=teste32 -Dspring.config.location=C:\workspace\myProject\target
Did you check content of target dir? I'm pretty sure your cfg file is placed to target\classes\xirulei and it is why Spring cannot find it in target
b) When you place teste32.yml in the same directory as jar file then Spring must be able to find it (given this directory is working directory) without -Dspring.config.location (but you still need to provide -Dspring.config.name=teste32)
c) When you use -jar and do not provide additional class paths then classpath: points to the root of packages inside jar. Spring cannot find your file at classpath:/ because your file is at classpath:/xirulei/
Well, after all it was a simple mistake. As documentation says and as already pointed here, it should be
java -jar myproject.jar --spring.config.name=myproject
and not
java - jar myproject.jar -Dspring.config.name=myproject
As stated on question, only when using Eclipse -D(JVM argument) is necessary. When using bash/cmd, just --(program argument) is the correct option:

Can we use windows bat file in Java jar file, so that java can run some windows command, if yes where we should keep bat file in side that jar file

I am trying to execute a windows command inside java code using Runtime.exec() command. It is working fine when put all the necessary batch file and properties file on the root directory. But when i am exporting this is as jar, the java program is throwing error, which is becuase it is not able to find all those dependent .bat and .properties files. Can some one please tell me, where should i keep all the .bat and .properties files in side the folder. Thanks in Advance.
You can do so
Something like
Runtime.getRuntime().exec("cmd /c start yourFile.bat");
You should be able to keep it in the root of your jar if you want
EDIT :
On second thought I don't think you can run bat files inside a JAR
you would have to extract it and then run it
Please give more information on what it is you want the bat file to be doing and I can update this answer maybe there is another way?
Your problem can be divided into two parts: get the bat from the jarand run it.
To get the bat from the jar, you will have to use the ClassLoader to get a resource. you can achieve this by using the method Class.getResource to get the URL or Class.getResourceAsStream to get an InputStream
Anyway, i dont' think you can run the bat from inside the jar. If you try and fail, my advice is to create a temp file, copy your bat into your temp file and run that file.
P.S: Class.getResource finds file in the classpath. If your file is not in your classpath, you won't be able to find it this way.
EDIT: i add the code i'm using to get resources from a general relative path, given the path exist both starting from you working directory and from the home of your jar. It works, i've been able to just pack every folder i need into the jar and ship the jar to another compute rwhere eveything worked fine.
public static URL getResource(String name) {
if ("jar".equals(Main.class.getResource("Main.class").getProtocol())) {
return Main.class.getResource(("\\" + name).replace('\\', '/'));
} else {
try {
return (new File(System.getProperty("user.dir") + "\\" + name)).toURI().toURL();
} catch (MalformedURLException ex) {
return null;
}
}
}
Main is a known class, in this case the class where this static method is. I first use it to get a known url, and see if i am executing from a jar. If i am, i use the getResource, otherwise i use the File api.
the structure i use is this
main_folder\
res\
src\
package\
and, in the jar
file.jar\
package\
res\
and i need to use both File api and getResource since in the rist case the res folder is not in my classpath. with a different structure probably only the getResource method is fine.
This should solve your problem of getting the bat file, you still need to see if you are able to run it, and if you are not, copy everything into a temp file and run the temp file instead.

Best to way execute a file internal to a java project

Suppose my project structure is:
/project
/src
/java
Util.java
/cpp
/bin
a.out
I'd like to execute a.out from within Util.java without hard-coding any absolute paths in my java file. What's the best way to go about doing this?
EDIT -- Here's what I ended up doing: I happen to be using autoconf as most of the code is c++. I defined a substitution variable like AC_SUBST([project_root], [$(pwd)]) in configure.ac and substituted it in a Config.java.in file.
Perhaps using a properties file to be loaded on deployment/running time depending on the nature of your app.
More about its use in this thread
How to use Java property files?
You're file path to a.out could be ../bin/a.out. And then execute the file using that path.
Below is some pseudo code that might help you.
// look for the executable in the current working directory
File executable = new File("a.out");
if( executable.exists()){
System.exec() .... etc
} else {
String location = YourMainClass.class.getProtectionDomain().getCodeSource().getLocation();
// write code to form a path name to the a.out based on the location of .jar file
}

Categories

Resources