20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
About viralpatel.net
Join Us
Advertise
Search
VIRALPATEL.NET
Home
Android
Java
Spring
Frameworks
Database
JavaScript
Web
More
Loading Java Properties Files
FOLLOW:
BY VIRAL PATEL OCTOBER 26, 2009
Java Properties files are amazing resources to add
information in Java. Generally these files are used to store
static information in key and value pair. Things that you do
not want to hard code in your Java code goes into
properties files.
Although there are multiple ways of loading properties file, I
OnePlus10000mAh
LenovoPowerBank
will be focusing on loading the resource bundle files from
class path resources. There are advantages of adding
properties files in the classpath:
RECENT POSTS
Spring 4 MVC REST Controller Example
(JSON CRUD Tutorial)
Spring 4 MVC Tutorial Maven Example
Spring Java Configuration
CellbellTMAppleiPadPro9HPremium
(197)
1. The properties files became a part of the deployable
Find Process ID of Process using a Port
in Windows
How to Embed Tomcat within Maven
Project Run Tomcat with Maven
code (e.g. JAR file) making it easy to manage.
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
1/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
2. Properties files can be loaded independent of the path
of source code.
Bootstrap Navbar Menu without
JavaScript
Let us see the simple way of Loading a property file in Java
code. There are two ways of loading properties files in Java.
1. Using ClassLoader.getResourceAsStream()
2. Using Class.getResourceAsStream()
In our example we will use both methods to load a
properties file.
Following is the content of sample properties file. The
properties file will be in package
net.viralpatel.resources .
MI
MINDY02AN10000MAH
POWERBANK(SILVER)
net/viralpatel/resources/config.properties
hello.world=HelloWorld
To load properties file using Classloader, use following code:
ONEPLUS10000MAH
POWERBANK
this.getClass()
.getResourceAsStream("/some/package/config.properties"
The Class.getResourceAsStream(name) returns an
Inputstream for a resource with a given name or null if no
resource with the given name is found. The name of a
MOTOGPLAY,4THGEN
(WHITE,VOLTE)
resource is a /-seperated path name that identifies the
resource. If the name with a leading / indicates the
absolute name of the resource is the portion of the name
following the /.
In Class.getResourceAsStream(name), the rules for
searching resources associated with a given class are
implemented by the defining class loader of the class. This
method delegates to this objects class loader. If this object
was loaded by the bootstrap class loader, the method
delegates to
ClassLoader.getSystemResourceAsStream(java.lang.String).
So in our example to load config.properties we will have a
method
loadProps1() .
privatePropertiesconfigProp=newProperties();
...
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
2/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
publicvoidloadProps1(){
InputStreamin=this.getClass().getResourceAsStream
try{
configProp.load(in);
}catch(IOExceptione){
e.printStackTrace();
To load properties file using Classloader, use following code:
this.getClass()
.getClassLoader()
.getResourceAsStream("some/package/config.properties"
The ClassLoader.getResourceAsStream(name) returns an
Inputstream for reading the specified resource or null if the
resource could not be found. The name of a resource is a /seperated path name that identifies the resource. The name
no leading / (all namea are absolute).
So in our example to load config.properties we will have a
method
loadProps2() .
privatePropertiesconfigProp=newProperties();
publicvoidloadProps2(){
InputStreamin=this.getClass().getClassLoader()
try{
configProp.load(in);
}catch(IOExceptione){
e.printStackTrace();
The folder structure of our example code will be:
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
3/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
The full Java code for testing
packagenet.viralpatel.java;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
importjava.util.ResourceBundle;
publicclassLoadPropertiesExample{
privatePropertiesconfigProp=newProperties();
publicvoidloadProps1(){
InputStreamin=this.getClass().getResourceAsStream
try{
configProp.load(in);
}catch(IOExceptione){
e.printStackTrace();
try{
configProp.load(in);
}catch(IOExceptione){
e.printStackTrace();
publicstaticvoidmain(String[]args){
LoadPropertiesExamplesample=newLoadPropertiesExample
sample.loadProps2();
sample.sayHello();
publicvoidloadProps2(){
InputStreamin=this.getClass().getClassLoader()
publicvoidsayHello(){
System.out.println(configProp.getProperty("hello.world"
Further Reading
Java ClassLoader API
Java World Smartly Loading Properties Files
Related Articles
1. Dynamic Class Loading using Java Reflection API
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
4/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
2. Dynamic Property Loader using Java Dynamic Proxy
pattern
3. Files-Directory listing in Java
4. Apostrophe creating problem in properties file in
java/struts
5. Creating ZIP and JAR Files in Java
6. iText tutorial: Merge & Split PDF files using iText JAR
7. How to execute a command prompt command & view
output in Java
Get our Articles via Email. Enter your email address.
Send Me Tutorials
Your Email
Tags:
Java
property-file
resource-bundles
Hyderabad
999 OYORoomsGachibowliMiyapurRoad
OYORooms
PREVIOUS STORY
NEXT STORY
Fantastic Bouncy Effect
Create your own Search
using jQuery/JavaScript
Engine(Interface) using
Google Custom Search
API
YOU MAY ALSO LIKE...
Inspect
your code
in Eclipse
using
Eclipse
Scrapbook
feature
Java MD5
Hashing &
Salting:
Secure
Your
Passwords
Oracle Java
JDBC: Get
Primary
Key of
Inserted
record
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
5/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
Eclipse:
Ignore not
declare
static final
serialVersi
onUID
warning
32 COMMENTS
rakesh juyal 26 October, 2009, 23:25
Such a long article for so simple thing.
Reply
JavaMan 27 October, 2009, 0:02
Interesante aqui te dejo mis dos Blogs. Aqui encontraras
cosas tambien muy interesantes:
http://viviendoconjavaynomoririntentandolo.blogspot.com
http://frameworksjava2008.blogspot.com
Saludos.
Reply
ppow 4 November, 2009, 17:36
Asking the class itself for resources seems weird to me. Is
there any way to get that by asking the System or by other
API not connected to the class you are using it in?
Reply
r4ds 9 November, 2009, 9:45
Hi..
To load the property file in Java I think, it is very easy to do it.
It will come in the form of directory when you are
downloading this files..
In Java 6 updated version, every properties class have been
existed, take help form there to fulfil the requirements.
Reply
muski 13 November, 2009, 11:27
Simple method to load properties file.
Properties props = new Properties();
props.load(new FileInputStream(config.properties));
String value = props.getProperty(prop1);
System.out.println(value);
System.out.println(props.entrySet());
Reply
sneha
17 September, 2013, 1:03
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
6/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
Thank you Muski .. useful one :)
Reply
test 14 December, 2009, 22:26
Thanks man,
awesome post.
helped me in reading the properties file outside the jar file.
Thanks again
Reply
Fishinastorm 28 July, 2010, 12:22
Hi Viral,
NIce post. HOw do store some modified properties to the file
in the same package as you mentioned. I used
FileOutputstream, but it creates a new properties file
elsewhere..i want the same properties file to contain the
modified valuesi am goign berserk with this
Reply
Sachin singh 3 March, 2011, 18:43
Thanks Dude
Very good Post.
I was struggling like anything.
My problem was to load dataset file from resource folder (in
DBUnit)
return new
FlatXmlDataSetBuilder().build(this.getClass().getResourceAsStream(/dataset.xml));
thanks again;
Reply
Misty 25 October, 2011, 16:46
Could you tell me how to include the properties file path in my
manifest? my properties file is in the resources folder. I need
to include this in the class path of the JAR file, so that if any
user wants they can modify the properties file externally and
it will reflect in the JAR file
Reply
Curioso 7 March, 2012, 22:16
Very good, thanks
Reply
Sathish Kumar 7 April, 2012, 1:42
This is very useful and very easy to understand. Thanks a lot
LOL
Reply
dave51
19 April, 2012, 19:03
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
7/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
Nice post. But I have to mantain a properties file out of
MyProject.war file. In my environment I have a deploy
directory to put the MyProject.war file, a log directory and a
conf directory to put configuration.properties file. Using this
good suggenstion configuration.properties file is embedded in
MyProject.war file. Any Advice?
Reply
Mekbib 5 September, 2012, 19:03
I have found it very helpful.
Thanks for posting.
Reply
Raja 23 November, 2012, 10:33
hi ,
how to use the same properties
file(net/viralpatel/resources/config.properties) into jsp page
using jquery.
Reply
lochan 20 January, 2013, 12:36
can we write multiple sql queries in properties file? if yes
then how to retrieve a single out of them.
Please reply asap
Reply
isa 31 March, 2013, 6:03
Hi,
Nice tutorial.
One potential issue that i observe here is that the name of the
properties files has been hard coded in the code. you could
get away by using -D option in the command line.
Isa
Reply
Michael Fernando 12 April, 2013, 11:34
Thanks. This cleared my confusion.
Reply
Lucia 20 June, 2013, 4:26
Hello !
I tried in Eclipse your code and gives:
Exception in thread main java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at
com.ion.ysura.garage.LoadPropertiesExample.loadProps2(LoadPropertiesExample.java:30)
at
com.ion.ysura.garage.LoadPropertiesExample.main(LoadPropertiesExample.java:14)
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
8/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
Can you help?
Reply
Lucia 20 June, 2013, 4:53
Sorry !
I fixed it !!
Do not start the path with /.
Do as:
prop.load(OpenGarage.class.getClassLoader().getResourceAsStream(com/ion/ysura/garage/resources/config.properties));
Good examples !!
Reply
Marco 20 June, 2013, 18:52
This approach doesnt work if the properties file is outside the
jar
Reply
FirstbloggerTricks.com 14 April, 2014, 13:20
Nice explanation dude , u made it like a piece of cake.
I found an interesting explanation here also , this guy
explained in a funny way or i shud say comic way dats what
he had given the title.
Reply
Kiko 6 May, 2014, 21:40
Thankx ! The snapshot of eclipse showed me something i was
really missing!
Great Article
Reply
nishant
Hi,
25 May, 2014, 16:06
Read from properties file with hard-code, everything works
fine but when I introduce framework ,it gives null pointer
exception why?
//Hard code
public class tt {
public static void main(String[] args) throws IOException {
Properties CONFIG= new Properties();
FileInputStream ip = new
FileInputStream(System.getProperty(user.dir)+//src//com//app//config/config.properties);
CONFIG.load(ip);
System.out.println(System.getProperty(user.dir));
System.out.println(CONFIG.getProperty(url_dbname));
}
}
Reply
nishant
25 May, 2014, 16:14
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
9/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
Try to read following code from properties file, generate null
point exception.
Please help and thanks in advance.
public class Test_Login extends TestBase {
public static void main(String[] args) throws SQLException {
String dburl=jdbc:mysql://localhost:;
String port=3306;
String dbname=/test;
String username=root;
String password= root;
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
System.out.println(establish connection db first test);
try {
Class.forName(CONFIG.getProperty(Db_driver)).newInstance();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn=DriverManager.getConnection(dburl+port+dbname,
username,password);
}
}
Reply
Nenad 25 May, 2014, 19:36
Could you please give your comment on this question on
StackOverflow?
http://stackoverflow.com/questions/23854130/eclipsejava-file-fileinputstream-vs-input-stream-when-loadingfont-file
You see, this (as you suggested) works:
fis=this.getClass().getClassLoader().getResourceAsStream
but this doesnt (neither in Eclipse nor in runnable JAR)
fis=this.getClass().getResourceAsStream("
In if I understood you post correctly the other option should
work as well?
Where did I go wrong?
Reply
srinath 26 May, 2014, 12:09
such a simple explanation is very easy to understand.Thanx a
lot man.
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
10/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
Reply
J Moore 6 June, 2014, 22:09
Thanks a lot! Your explanation was the first one I could find
that actually spelled out how to get Class.getResource(foo)
working in Eclipse. I havent read through all the comments,
so I may be repeating things: this technique works for
anything you want loaded into a Java application in a non
path-dependent way. I am using it to load an ICC color table,
for instance.
Reply
hardik 23 June, 2014, 12:07
Can i achieve localization ?
Reply
vinodjai 26 November, 2014, 19:04
Thanks for sharing a good example.
Can you please share about how to update property file
inside a jar ?
Writing back is little difficult when file is inside the jar. I tried it
using below code but can not achive it.
URLourl=this.getClass().getResource("/config
config=newPropertiesConfiguration
config.setProperty("lastupatedtime
config.save();
this work fine when file is outside the jar.
Reply
Mateen 29 June, 2015, 19:43
Thanks for the blog
Reply
Mark 1 September, 2016, 18:58
I tried your example and I keep getting a null returned in the
stream. Im using RAD 8.5 and WAS 8.5. My properties file is
under my Resources java project which is at the same level as
the calling method:
* EmailPrefJava
->Java Source
->com.usb.emailpref.util
->GenericPropertyManager.java
->Public GenericPropertyManager
InputStream inputstream =
this.getClass().getResourceAsStream(/local/projects/emailpreferences/properties/emailpref.properties);
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
11/12
20/09/2016
LoadJavaPropertiesFiles.LoadingPropertiesFilesinJava.PropertiesFile
* Resources
->Local
->projects.emailpreferences.properties
->emailpref.properties
Ive tried the following:
1) removing the leading slash from the path,
2) prefacing the path with /Resources,
3) removing all the folder references and leaving just the
properties file name,
4) changing projects/emailpreferences/properties to
projects.emailpreferences.properties
5) replaced the relative path with a direct path
d:\\projects\emailpreferences\properties (and the file does
exist there).
The reason I dont use the direct path is we have to move the
properties files into the apps EAR and now need to reference
it from there.
Id really appreciate your help. Yours is the closest example
Ive found of what we need.
Reply
LEAVE A REPLY
Comment
Name *
Email *
Website
Post Comment
ViralPatel.net 2016. All Rights Reserved.
http://viralpatel.net/blogs/loadingjavapropertiesfiles/
12/12