How to Load properties file present in a JAR? - java

I have below piece of code in my Utility class which is in a .jar file. When I run the code in a local system it works fine, but when I run the JAR file using command, java -jar dbConnection.jar, it is unable to recognize jdbcDetails.properties file.
Properties prop = new Properties();
prop.load(Utility.class.getResourceAsStream("jdbcDetails.properties"));

Extract (unzip) the dbConnection.jar File and make sure 'jdbcDetails.properties' is present
Make sure 'jdbcDetails.properties' is located next to 'Utility.class'

Related

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 to make a runnable jar for a java project with properties files will be editable at runtime?

My maven project is a standalone java appplication. I need to run this form a Unix box. So i made a runnable jar.But i have to update a date in the app.properties file in every run.I tried maven jar plugin to make a fatty runnable jar with all dependency. It is running fine , but not able to edit the app.properties file
You can read a properties file from the classpath (root package) like this:
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("/app.properties")));
You can start a runnable jar with a custom classpath like this:
java -cp app.properties:app.jar my.main.AppClass
(you cannot use java -jar because then the -cp option is ignored)
Put the file app.properties in the same directory as app.jar. The location of app.properties will be the first entry on the classpath and thus the code in the jar can load it as shown above.
If you make sure there is also a copy of app.properties in the jar, then that will be used as default if the external properties file is missing. (note that this only works for the complete properties file, not for individual properties)

How to maintain a configuration file in java application project like a configuration file in C# application?

In C#,when I want to create a configuration file, it's so easy,just right click the mouse and add a new configuration file, this file will be added into the solution and it's so easy to maintain.
But in java, I don't know what method is standard. I see some people use the properites file.If this is the most popular method, can some one tell me where to place this file? I saw some guy put it in the src folder, others put it in an external folder.
Can you tell me which is the standard? And what is the best practice to maintain a configuration.
I don't know if this is the "standard" way but I think it's the easiest. If you place your properties file in your project's root folder
- project
- config.properties
- src
- main
- ...
- test
When you create a File instance in Java and specify a relative filename, then the name is resolved against the directory that Java was launched from
e.g. if you launch java in your command prompt as follows:
cd C:\Users\Tom\example-project
java example-project
and this is your code:
File file = new File("tom.txt");
then the file variable will be resolved to the abolsute path: C:\Users\Tom\example-project\tom.txt
When you Run a project through Eclipse, Eclipse launches java from the root directory of the project, meaning that if you put your config file in the project's root folder then
File file = new File("name-of-config-file.properties");
will resolve to the correct config file on your system.
This has an added benefit if you create a runnable JAR, as you can just place your config file in the same directory as your JAR and the code will continue to work (the config file location will be resolved relative to the JAR).
If you put your config file in /src folder then you need to have separate code for when running from Eclipse and when running as a JAR
With regards to sample code:
//Read properties from disk
File propertiesFile = new File("config.properties");
FileReader reader = new FileReader(propertiesFile);
Properties props = new Properties();
props.load(reader);
//Set and get properties
props.setProperty("NewProperty", "value");
String propValue = props.getProperty("propToGet");
//Write properties to disk
FileWriter writer = new FileWriter(propertiesFile);
props.store(writer, "Added x properties");
Configuration files are used to store,read write user settings.
I think for web apps you can use web.xml.And for other you should use Properties class to read and write settings.
As for where to place it,If you dont specify path it is stored in your root folder other than that you have to provide explicit path.

Including a property file with the Jar file in a single folder

I am creating a java application in Eclipse Helios.I have created a class in which i need to have data from the .properties file which i added in the folder containing the solution .Through this code i can accesss the value from the .properties file when i try to run it in Eclipse.
The code is:
Properties prop = new Properties();
prop.load(new FileInputStream("config.properties"));
_url = prop.getProperty("url");
Through this code i am getting the correct value of the Url .
After this i have created an executable jar of my project .When i tried to execute the jar using command line then i got a FileNotFoundException ,means the jar is not able to locate the .properties file.
I have kept the .properties file in the same folder as of Jar file as we have the provision of editing the .properties file.
Since i started working in Java for only 4 days ,i am unable to figure out about where to place the .properties file and how to access it.
Please help.
For jar try to use:
prop.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
if you call from static context use:
prop.load(YourClassName.class.getClassLoader().getResourceAsStream("config.properties"));
You need to ask the class loader to get a resource.
See http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html
Properties prop = new Properties();
prop.load(classLoader.getResourceAsStream("config.properties"));
_url = prop.getProperty("url");

Confused about java properties file location

I have simple java project with structure:
package com.abc:
a.java
b.java
c.properties
I have database configuration parameters configured in c.properties file.
Inside a.java and b.java, I am loading properties file using:
Properties p = new Properties();
InputStream in = this.getClass().getResourceAsStream("c.properties");
p.load(in);
This works fine. But the main question is, once I prepare executable jar by exporting this code, properties file also gets packaged in jar file. If someone else wants to modify properties file for different database configuration, how can he do it?
Do I have to store properties file in some fixed location in local machine. e.g. "c:/". Then give jar along with properties file to the other person. Then he needs to copy properties file inside C:/ location?
Also one more question, how can i make this location generic for windows and linux machine?
The typical way of handling this is to load the base properties from your embedded file, and allow users of the application to specify an additional file with overrides. Some pseudocode:
Properties p = new Properties();
InputStream in = this.getClass().getResourceAsStream("c.properties");
p.load(in);
String externalFileName = System.getProperty("app.properties");
InputStream fin = new FileInputStream(new File(externalFileName));
p.load(fin);
Your program would be invoked similar to this:
java -jar app.jar -Dapp.properties="/path/to/custom/app.properties"
First keep the default properties in your properties file, which gets packed into the jar. When the application starts try reading a same named properties file from some default location in filesystem, preferrable the user's home folder which you can obtain by System.getProperty("user.home");. If the file exists at the filesystem load it, if it doesn't exist then load your packed properties file and write a copy to the filesystem.
So if your properties file name is myprops.properties, initially only your jar file will contain it. When the application starts up it will check whether /home/xyz/myprops.properties file exists. Since it doesn't, it will read the packed properties file and write a copy to /home/xyz/myprops.properties file. From next time onwards, it will read from /home/xyz/myprops.properties.
Why not pass the location of the properties file as a command line argument (following a flag)? if it's not present, then use the default one in the jar file.
You're loading the properties file from the class path. I'd suggest something like this:
Properties location

Categories

Resources