Normally, Java properties file is used to store project configuration data or settings. In this tutorial, we will show you how to read and write to/from a .properties file.
Properties prop = new Properties();
// set key and value
prop.setProperty("db.url", "localhost");
prop.setProperty("db.user", "mkyong");
prop.setProperty("db.password", "password");
// save a properties file
prop.store(outputStream, "");
// load a properties file
prop.load(inputStream)
// get value by key
prop.getProperty("db.url");
prop.getProperty("db.user");
prop.getProperty("db.password");
// get all keys
prop.keySet();
// print everything
prop.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));
A simple Maven project structure for testing.
1. Write to the properties file
Set the property key and value, and save it somewhere.
package com.mkyong;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class App1 {
public static void main(String[] args) {
try (OutputStream output = new FileOutputStream("path/to/config.properties")) {
Properties prop = new Properties();
// set the properties value
prop.setProperty("db.url", "localhost");
prop.setProperty("db.user", "mkyong");
prop.setProperty("db.password", "password");
// save properties to project root folder
prop.store(output, null);
System.out.println(prop);
} catch (IOException io) {
io.printStackTrace();
}
}
}
Output
{db.user=mkyong, db.password=password, db.url=localhost}
The path/to/config.properties is created.
#Thu Apr 11 17:37:58 SRET 2019
db.user=mkyong
db.password=password
db.url=localhost
2. Load a properties file
Load a properties file from the file system and retrieved the property value.
package com.mkyong;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App2 {
public static void main(String[] args) {
try (InputStream input = new FileInputStream("path/to/config.properties")) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("db.url"));
System.out.println(prop.getProperty("db.user"));
System.out.println(prop.getProperty("db.password"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output
localhost
mkyong
password
3. Load a properties file from classpath
Load a properties file config.properties from project classpath, and retrieved the property value.
db.url=localhost
db.user=mkyong
db.password=password
package com.mkyong;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App3 {
public static void main(String[] args) {
try (InputStream input = App3.class.getClassLoader().getResourceAsStream("config.properties")) {
Properties prop = new Properties();
if (input == null) {
System.out.println("Sorry, unable to find config.properties");
return;
}
//load a properties file from class path, inside static method
prop.load(input);
//get the property value and print it out
System.out.println(prop.getProperty("db.url"));
System.out.println(prop.getProperty("db.user"));
System.out.println(prop.getProperty("db.password"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output
localhost
mkyong
password
4. Prints everything from a properties file
Load a properties file config.properties from project classpath, and print out the keys and values.
package com.mkyong;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;
public class App4 {
public static void main(String[] args) {
App4 app = new App4();
app.printAll("config.properties");
}
private void printAll(String filename) {
try (InputStream input = getClass().getClassLoader().getResourceAsStream(filename)) {
Properties prop = new Properties();
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
prop.load(input);
// Java 8 , print key and values
prop.forEach((key, value) -> System.out.println("Key : " + key + ", Value : " + value));
// Get all keys
prop.keySet().forEach(x -> System.out.println(x));
Set<Object> objects = prop.keySet();
/*Enumeration e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
}*/
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output
Key : db.user, Value : mkyong
Key : db.password, Value : password
Key : db.url, Value : localhost
db.user
db.password
db.url
Useless. Overwrites the whole file.
Can we read from class path and store in the same class path with different file name.
I need to update the application.properties with the application-prod.properties
Can .load be used to read a property file of another Java app within the same package? Like I want to read the other java apps .property file, create an Enum Map of key value pair and then compare it to the property file in the calling Java app. Thanks
Don’t you have to close the stream ? e.g. in finally ?
Can you share the ide theme name plz
Muito obrigado !!!
How to read and write .cfg file in java?
I included this as a jar in my main application. Not getting any errors but I am unable to see .properties file being created on liberty server and subsequently properties not getting loaded in other java files.
Thansk , I found this very useful
Well done
Hello, i’m new to java, can u tell me what’s the different between point 2 (Load a properties file from the file system) and point 3 (Load a properties file config.properties from project classpath), and can you suggest me when i should use point 2 or point 3 ? Thank you very much.
i want to read from config.properties and store it into new environment.properties. anyone help
Is that possible to add the property name on the run time, which the existing property file dosent have such value.
Yes, see App1 example.
@Mkyong you are a living legend!!!
I can’t find config.properties file. Can anyone help me ?
you can either give the exact directory or go one level higher i.e. src/main/resources/config.properties
You need to add to the project manually. ???
Article is updated, for App1 and App2, you need to defined your own location, by default it will saved into the project root folder.
For App3, it loads from
src/main/resources/config.propertiesOhhh man that you can create by your ownan that’s easy part
how to add html tags and affect in front-end through resource bundle file, Ex: i need to show bolder text front-end, i tried BOLDER but it doesn’t work.
Hat mir sehr geholfen. Danke..
“input = App3.class.getClassLoader().getResourceAsStream(filename);”
What is App3?
App3 is mistake there. It should be App.
That means the name of class thats all.
Article is updated, App3 is the class name.
Thanks a lot
Hi Kyong, Can you please explain how to use properties file in Java web application. And how to pass when running the same from server(Glassfish)
My file is not getting picked up for reading. Please give me some suggestion
In your third example, you write:
input = App3.class.getClassLoader().getResourceAsStream(filename);
This should probably be App.class ….
Also, I believe that for AutoCloseable streams the following approach is a good practice:
final String PROPS = “main.properties”;
final Properties properties = new Properties();
try (final FileInputStream in = new FileInputStream(PROPS)) {
if (null != in) {
properties.load(in);
} else {
throw new IOException(String.format(“file %s not found in classpath”, PROPS));
} catch (IOException e) {
System.out.printf(“Loading of properties was not performed, reason: %s%n”, e.getMessage());
}
Or for resources:
final String PROPS = “main.properties”;
final Properties properties = new Properties();
try (final InputStream in = getClass().getClassLoader().getResourceAsStream(PROPS)) {
if (null != in) {
properties.load(in);
} else {
throw new IOException(String.format(“file %s not found in classpath”, PROPS));
}
} catch (IOException e) {
System.out.printf(“Loading of properties was not performed, reason: %s%n”, e.getMessage());
}
static public void main(String args[]) throws IOException {
Properties prop = new Properties();
InputStream input = new FileInputStream(“F:\workspace\Practice\config.properties”);
prop.load(input);
Set set = prop.keySet();
for (Object r : set) {
System.out.println(r + ” value is: ” + prop.getProperty((String) r));
}
}
a simple way to have key value pair printed
i followed the tutorial, using this code:
1. Write to properties file
tested the code on a tomcat but not create the file why? how to know why?
2) in wich path was created the file?
my tomcat is installed on /opt/tomcat
not i tested sam ecode on a glassfish server and worked, created the file on:
/opt/glassfish4/glassfish/domains/swManzana/config/
and i am happy but in tomcat why not work?
thanks
Good Article!!
Thanks!
worked fine.
how do i preserve the existing comments in the properties file, while still modifying a key value pair or two ?
Hi, is there a way to put properties in the GUI admin console from glassfish and get it via @Resource?
can we load property file values in netbeans reading property file from command line arguments
it is possible to use variables into a properties file? something like this:
key=value1
key2=value3
key3=${value2}${value3}
HI, Thanks for the tutorial, can u tell me how to set the Labels of a JSP page using Properties File, ???
Hi,
I’m always getting “Sorry, unable to find ” + filename in scenario 4
Note: I have a properties file which works just fine with scenario no. 2
Can you please help?
For App4, it loads fro
src/main/resources/config.propertiesThanks for the post. I have a maven project with JPA, and I want the persistence.xml file is set with a data connection, you are in a properties file. Thanks for your help.
Great example. Better than find in own past code.
I see how to read from the classpath but what about writing to it?
Refer to App1 and App2 examples.
can anyone help me how to retrieve pdfs from path stored in database
sir i need simplry programme of properties file pls reply my emaid:[email protected]
Hi, thanks for the examples.
You can still improve the “input.close()” part with the JAVA 7 “try-with-ressource” statement :
example :
try (InputStream input = new FileInputStream(PROPERTIES_FILE_NAME)) {
properties.load(input);
// (…. do some stuff …)
} catch (IOException e) {
e.printStackTrace();
} finally {
// don’t have to care about input.close() anymore here
}
Explained here http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Thanks! Great post!
Thanks 🙂
Maybe you should set the properties as the System one’s, i.e.:
prop.load(input);
System.setProperties(prop);
?
Thanks for the post. I have an issue. i am encrypting the password and storing in properties file. my input is admin123, after encryption it is “9GkMVi65yhKkf5PoVaFEWw==”, But after write to properties file it is showing like “9GkMVi65yhKkf5PoVaFEWw==”. Could you please suggest me to solve this. Thanks
Hi mkyong,
In my Java application I have been using similar code and I have issues with memory leak. To be precise, I have a helper class which has all static methods and in one of the static method, I load properties file but instead of readying key values in this method, I return “Properties” object to calling method. Calling method then reads key/values and does nothing to this returned properties (I mean no memory cleanup). Also in static method where I load properties file, I am not closing the “InputStreamReader”. My questions are:
1) Will this lead to memory leak?
2) If I close the “InputStreamReader” immediately after loading properties file, will the caller have access to all key/values? Is it a good practice to close stream reader immediately after it is used?
how to sort based on alphabet key name, because when I create properties file is unsort by alphabet….
Anyone can tell me ???
Thank you
Thanks.
thanks nice job 🙂
If you want to preserve comments in your properties files. Have a look at the class/library I have made. (open source)
http://jhpropertiestyp.sourceforge.net/jhpropertiestyped/javadoc/dk/heick/properties/types/utils/CommentedProperties.html
http://jhpropertiestyp.sourceforge.net/
The load method doesn’t close the input stream you give it. The input stream must be closed after the properties are loaded. Many people might follow the example and leave that leak in their code.
Thanks, examples are updated with the ugly close steam statement.
Since you wrote this in 2014, I suggest to use the language features provided by at least JDK 1.7, which for the case of AutoCloseable objects suggests to use the try-with-resources approach (http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). I’ve also left a comment regarding this further above.
Article is updated again, auto close now.
I have a .properties file. I have to create a jsp page such that it reads the data from this .properties file and display it in table format.
My .properties file s something like ERORECORDS = 600 DELAZERORECOS = 30 ANSYTIM = 900 DEDDEMADF = DEDREGF_ACUV DEDDEMAE = DEDREFG_REOG DESDPWDS = DEDCHGG_PWDP
and goes on… I have to create a jsp page to show these data in a table format
please help me
Look at mkyongs tutorials on Spring MVC. You’ll be able to pass the values from the properties file into the JSP view from the controller.
always there to help one in need 🙂 thank mkyong
getting NullPointer exception in the 3rd scenario:-
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.properties.reader.AppReaderCpath.main(AppReaderCpath.java:15)
Create a dummy “config.properties” file, and put it in your project classpath.
Thanks a lot..
Your blog is in my help list.. 🙂
Hi,
Thanks for the tutorial, it works for me when create servlet and deployed in tomcat. But I got NullPointerException in weblogic, The path for the properties file is in WEB-INF folder. Maybe you know why it failed?
regards,
Ruly
Clear and easy like Rafael said. Thanks a lot.
Your tutorials are always so good. Short sweet and to the point, thanks man.
My thoughts exactly
Thanks MkYoung, explanation clear and easy .
This was so lucid and concise.
You just saved half hour of my life by writing this article.
May the force be with you!
Best!
Vijai
I am writing testscripts and i saved all my datas in data.properties file. i added lot of comments and left some spaces between each datas. To run my scripts i need to update the property file and i tried the option
for example ::
prop.setProperty(“dbpassword”, “password”);
prop.store(new FileOutputStream(“config.properties”), null);
But after saving it deletes all the commented text and it rearrange the datas in it.
Thanks for such a clear example
Thank you so mutch, I just love this website, and you are not a computer that is printing(docs.oracle writes like a computer). Thank you again 🙂
Im from sweden so my spelling isn’t that good
Thanks! you are doing a very good job for the Java community. Each time I forget how to do something, I look you up and I find what I need.
Thanks, I’m doing the same, always 🙂
Me tooo , thanks
You look yourself up and find what you need each time you forget how to do something? What a reference you must be! 😛
I like this posts
Thanks!
Thanks!
Perfect! Thank you. Very well written.
I am typically to blogging and i actually respect your content. The article has actually peaks my interest. I’m going to bookmark your web site and hold checking for brand new information.
I completely agree.
EVERY SINGLE article I have read so far has been extremely helpful and straight to the point.
Thanks. Keep it up
Thank you! It’s useful!
Thank you! Your site is really helpfull!)))
Thanks,
Really Helped me.
thanks
Thank you
Hi All,
Can anyone please help me in finding out what all system properties are available during recovery time ?
The System properties for eg: ro.product.xxx that are available,when the device is fully booted up , is different from when the device is in recovery mode.
The requirement is to access few system properties during recovery mode.
Thanks in Advance !
Please define the ‘device’ and ‘recovery time’
thx
Device = Android Tablet
Recovery Time = I didn’t get this. This recovery mode is same as when
we see the recovery screen for OTA updates.
Hi MK,thanks for your post,but my requirement is little different.I want edit an existing property file at runtime.Suppose there is key value like name=sanjib but at runtime i want to change it to name=sanjibdhar.Is it possible and how??
i want to read the metadata of TIFF image.Can u plz tel me dat how would it possible by using JAVA ADVANCED IMAGING(JAI).
Just wanted to say that THIS IS AWESOME. I’ve been looking for straight-up source code on how to do this for a while. Perfect. THANKS!
five. Keep nasal passages clear
Hello,
I am trying to make the property file, but while i am adding any special character in the value of the key value pair, it appends a ‘/’ in front of that.
like
prop.setProperty(“database.url”, “jdbc:oracle:thin:@localhost:1521:xe”);
but in the property file, it is stored as
database.url=jdbc\:oracle\:thin\:@localhost\:1521\:xe
Please help, its quite urgent.
Thanks in advance
The \ character is added to escape the specials chars like :. If you test your code with a simple
System.out.println(prop.get("database.url"));you will see that your property is as expected, without \ char.
Thnx for the reply, but I want to write that in the property file as it is(*its kind of requirement), and the ordering is also not right. Its getting saved randomly.
I want it to be in the manner, I am writing it.
So, any help on this..???
I think properties are optimized internally with storing algorithm, that’s why the value is
put randomly in the file. If you want to write to a file with the certain structure just write to it as on a normal file. Like here http://www.exampledepot.com/egs/java.io/WriteToFile.html. Also read this about what you can and can’t do with a properties file:
http://docs.oracle.com/javase/tutorial/essential/environment/properties.html
Gracias !!!!
thanks for the post. I am trying to read all my xpaths for selenium. This post helped me
When I write my Properties to a file, there is always a ‘\’ at the 40th character of each key-value pair. But the properties file work perfectly after reading back. Why?
How to store property in the following format:
property1_name = list_of_values1
property2_name = list_of_values2
I use Properties.store() method to store my properties. But it was add a ‘\’ at the 40th characters of each line, i.e. My…..Properties.lastDate2=30/07/2012 13\:35
I read back the file with Properties.load() and it works perfectly. Is there a way to get rid of the ‘\’?
thank you for the examples
Thanks you so much …you posts helped me a llot..plz keep up the good work 🙂
Thank you so much…you saved me from lots of unnecessary hard work..had searched for solution at so many places but your posting helped me greatly …thanks
Hi,
How to remove the timestamp added to the file, on writing?
could you explane what this part of code in .properties file will do?
logPropFileName = D:\\Program Files\\Corillian\\DMS-PA\\conf\\PA-log4j_cnet.properties
paHistoryFile=D:\\FTP_Dir\\Current\\PaymentHistoryCNet.xml
paReturnFile=D:\\FTP_Dir\\Current\\ReturnCNet.xml
paRejectFile=D:\\FTP_Dir\\Current\\RejectCNet.xml
paCheckFile=D:\\FTP_Dir\\Current\\CheckCNet.xml
I am goning through the some BAT files and i am not getting this part
com.corin.pa.facade.CheckUpdateFacade d:/”program files”/Corin/DM-PA/scripts/system_b.properties
what does this part is doing actually?
Hi,
to my understanding of file operation, when loading properities from a file, the FileInputStream shall be closed.
FileInputStream fin; try { //load a properties file fin = new FileInputStream("config.properties"); prop.load(fin); //get the property value and print it out System.out.println(prop.getProperty("database")); System.out.println(prop.getProperty("dbuser")); System.out.println(prop.getProperty("dbpassword")); } catch (IOException ex) { ex.printStackTrace(); } finally { fin.close(); }There should be added 2 more things, fin should be initialized and the close operation should be on try catch:
pre lang=”java”>
FileInputStream fin = null;
try {
// load a properties file
fin = new FileInputStream(“config.properties”);
prop.load(fin);
// get the property value and print it out
System.out.println(prop.getProperty(“database”));
System.out.println(prop.getProperty(“dbuser”));
System.out.println(prop.getProperty(“dbpassword”));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
fin.close();
} catch (IOException e) {
}
}
thank you
how should i update the .property file by a user interface html form..?
This worked right out of the box. Perfect.
hello
I need to get only the three first lines of a .properties file in Java.
The problem I am facing is that I’m getting all the lines of the file with that method:
public void displayProperties(Properties props) { Iterator it = props.keySet().iterator(); while (it.hasNext()) { //propertyName = (String) it.next(); propertyName = (String) it.next(); propertyValue = props.getProperty(propertyName); }I need to fill in an array with the three first properties I get, so how can I read only the three first lines?
instead of a while, u can use a for.
Hi All,
Please refer the below mentioned blog.. Solves the problem of FileIOnotfoundException
It;s simple technique to create a new package and include the property file within it..
So that makes the property file available within the JAR file.
http://viralpatel.net/blogs/2009/10/loading-java-properties-files.html
Thanks,
Ranjan
That did it. Thank you.
Peter
i am sorry my prev message i could nt see properly that is why i’m giving again
i added the class path as whole path, and also from project
value=”classpath:/home/dev06/filesys/config/info.properties”
and
value = “classpath: filesys/config/info.properties”
i am getting FileIOnotfoundException and it cound nt read or load
I have the same problem in a netbeans project. I’m trying to read the config file from another folder (actually a package) in the project, so I’ve got:
main project folder (package)
|
+- main class
|
+- sub-folder (package)
| |
| +- java file from which the call to load the properties file is made
|
+- sub-folder (package) for the properties
|
+- properties file
I’ve tried every type of relative path I can think of:
* config.properties
* properties/config.properties
* ../properties/config.properties
* ../../properties/config.properties
… and some more, but nothing seems to work. I still get a file not found exception.
Any suggestions gratefully received.
Cheers
Peter
Below code works if your .properties file is present in src/main/resources folder
and this code does the trick to keep ur .properties file out side src and u can customize at any point of time
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="file:${config.files.dir}/information.properties" /> </bean>in this way
Thanks. I guess that works if you’re using a framework, but I’m not. It’s just a plain vanilla (NetBeans) Java project.
(I couldn’t find a framework for Java that wasn’t either Web or Java EE centric).
Cheers
Peter
Hello, how to read .properties file, present in outside the src folder
for example i have a .properties file. i dont want to keep this in src folder, so i created a new folder config, and i added my .properties file
i gave code as class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>
and also class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>
but still i am gettingthis message
Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [resource/Information.properties] cannot be opened because it does not exist
any help will be appreciated
This is Nice.
Simple and Straight 🙂
very helpful.Thanx
You should close the stream used to write the properties to once you’re done writing.
http://helpdesk.objects.com.au/java/how-to-store-values-in-a-properties-file
Quick question, what if I would like to write to the file multiple times. I tried this solution, but it creates a new file and I loose previous written sections.
Thanks,
Homer
can i have your code ?
thanx for your examples
Always find your hints/notes (no matter how small) very helpful!!!
Any advice on loading properties several directories up? Unfortunately relative and “../” format for going back a directory doesnt seem to work.
really so good .i think this type of sample will be very useful to all
Hi i nee small information reg to properties file in struts1.3
i want to add some extra msg to properties file is it possible?????if s kindly reply me ASAP
i want to print action message like “20 records inserted successfully” here 20 is dynamic i don’t know the exaact value……
Swathi.. go throw this link…
http://www.coderanch.com/t/531584/Struts/change-key-value-pair-properties