- How to Read Config File in Java – With Actual Class Example rovided
- The Config File Class
- Related Posts
- How to Read Config File in Java – With Actual Class Example rovided
- The Config File Class
- Related Posts
- Reading and writing configuration for Java application using Properties class
- 1. Creating a Properties object
- 2. Loading properties file
- 3. Getting properties values
- 4. Setting properties values
- 5. Saving properties file
- 6. Sample Swing application
- Other Java Coding Tutorials:
- About the Author:
How to Read Config File in Java – With Actual Class Example rovided
In my last post I mentioned “Config Class”couple of times.. here you will see actual class and its usage. The class is very simple. We just need to provide proper path to config file we going to use.
The Config File Class
You can get any property/settings from config with method ‘getProperty’
Here is my config sample file
I hope you find this useful. If you wish to read more Java articles from our site visit this.
Related Posts
very helpful and clean. Maybe few comment can add more value usage
Config cfg = new Config();
String dbname = cfg.getProperty(“mDbUser”);
hello, i need to develop a component java/j2ee that will serve to compare 2 configurations of two projects and then do the impact.
Someone help me please to identify my classes and do my class Diagram.
And here is the Singleton version:
import java.util.Properties; public class Config < private Properties configFile; private static Config instance; private Config() configFile = new java.util.Properties();
try configFile.load(this.getClass().getClassLoader().getResourceAsStream(“config.cfg”));
> catch (Exception eta) eta.printStackTrace();
>
> private String getValue(String key) return configFile.getProperty(key);
> public static String getProperty(String key) if (instance == null) instance = new Config();
return instance.getValue(key);
>
> Usage:
$value = Config.getProperty(key);
Is it possible to load the config file from a file on the file system? Like System.getProperty(“user.homer”)+”/myconfig.cfg” ?? Hope for reply, thanks!
Yes, you can load config from a file on the file system. here it is how you can do it
Properties prop = new Properties();
prop.load(new FileInputStream(«c://config.properties»));
System.out.println(prop.getProperty(«name_of_variable_in_config»));
You can also refer our article Write Config File in Java Thanks for stopping by. See you around!
Everyone loves what you guys tend to be up too. This type of clever work and coverage!
Keep up the terrific works guys I’ve included you guys to our blogroll.
Hello do you by any change have one of these formats to write to a cfg file in one of the field cfg = new WriteConfig();
cfg.setProperty(“mDbUser”) = myuser
Not at the moment.
I did not understand how you going to use this functionality, just to prepare properties file? OR you want to load the updated properties file runtime?
I have past the same code as above, only thing i have changed is the name of the config file but am getting the following error.
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)
Suppose my code requires to store multiple user name.
I did normally i.e.
db.user=user1
db.user=user2
.
.
.
. but it is extracting the last user only Plz suggest me some alternative
@mayank99
Properties file is simply a set of key value pair. If you assign multiple values to same key the latest assignment is going to override previous one. You can assign users as comma separated list and then fetch and process it to give you list of users.
e.g.
db.user=user1,user2
How to Read Config File in Java – With Actual Class Example rovided
In my last post I mentioned “Config Class”couple of times.. here you will see actual class and its usage. The class is very simple. We just need to provide proper path to config file we going to use.
The Config File Class
You can get any property/settings from config with method ‘getProperty’
Here is my config sample file
I hope you find this useful. If you wish to read more Java articles from our site visit this.
Related Posts
very helpful and clean. Maybe few comment can add more value usage
Config cfg = new Config();
String dbname = cfg.getProperty(“mDbUser”);
hello, i need to develop a component java/j2ee that will serve to compare 2 configurations of two projects and then do the impact.
Someone help me please to identify my classes and do my class Diagram.
And here is the Singleton version:
import java.util.Properties; public class Config < private Properties configFile; private static Config instance; private Config() configFile = new java.util.Properties();
try configFile.load(this.getClass().getClassLoader().getResourceAsStream(“config.cfg”));
> catch (Exception eta) eta.printStackTrace();
>
> private String getValue(String key) return configFile.getProperty(key);
> public static String getProperty(String key) if (instance == null) instance = new Config();
return instance.getValue(key);
>
> Usage:
$value = Config.getProperty(key);
Is it possible to load the config file from a file on the file system? Like System.getProperty(“user.homer”)+”/myconfig.cfg” ?? Hope for reply, thanks!
Yes, you can load config from a file on the file system. here it is how you can do it
Properties prop = new Properties();
prop.load(new FileInputStream(«c://config.properties»));
System.out.println(prop.getProperty(«name_of_variable_in_config»));
You can also refer our article Write Config File in Java Thanks for stopping by. See you around!
Everyone loves what you guys tend to be up too. This type of clever work and coverage!
Keep up the terrific works guys I’ve included you guys to our blogroll.
Hello do you by any change have one of these formats to write to a cfg file in one of the field cfg = new WriteConfig();
cfg.setProperty(“mDbUser”) = myuser
Not at the moment.
I did not understand how you going to use this functionality, just to prepare properties file? OR you want to load the updated properties file runtime?
I have past the same code as above, only thing i have changed is the name of the config file but am getting the following error.
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)
Suppose my code requires to store multiple user name.
I did normally i.e.
db.user=user1
db.user=user2
.
.
.
. but it is extracting the last user only Plz suggest me some alternative
@mayank99
Properties file is simply a set of key value pair. If you assign multiple values to same key the latest assignment is going to override previous one. You can assign users as comma separated list and then fetch and process it to give you list of users.
e.g.
db.user=user1,user2
Reading and writing configuration for Java application using Properties class
This tutorial will help you getting how to use the Properties class for reading and writing configuration for your Java applications. And at the end, we have a sample Swing application that demonstrates reading and writing configuration for database settings.
Table of content:
.properties format XML format
First, let’s look at two small examples:
The following code loads config.properties file and read out a property called “host”:
File configFile = new File("config.properties"); try < FileReader reader = new FileReader(configFile); Properties props = new Properties(); props.load(reader); String host = props.getProperty("host"); System.out.print("Host name is: " + host); reader.close(); >catch (FileNotFoundException ex) < // file does not exist >catch (IOException ex) < // I/O error >
The following code writes value of a property to the config.properties file:
File configFile = new File("config.properties"); try < Properties props = new Properties(); props.setProperty("host", "www.codejava.net"); FileWriter writer = new FileWriter(configFile); props.store(writer, "host settings"); writer.close(); >catch (FileNotFoundException ex) < // file does not exist >catch (IOException ex) < // I/O error >
1. Creating a Properties object
Properties props = new Properties();
Properties defaultProps = new Properties(); // set default properties. // create main Properties object Properties props = new Properties(defaultProps);
The default Properties object would be useful if you want to have a list of default properties which can be used when some properties do not exist in the physical file.
2. Loading properties file
We can load the properties file ( .properties or XML) using either subclasses of java.io.Reader class or java.io.InputStream class. Following are some examples:
- Load properties from a .properties file using a FileReader object:
File configFile = new File("config.properties"); FileReader reader = new FileReader(configFile); Properties props = new Properties(); // load the properties file: props.load(reader);
File configFile = new File("config.properties"); InputStream inputStream = new FileInputStream(configFile); Properties props = new Properties(); props.load(inputStream);
props.loadFromXML(inputStream);
InputStream inputStream = MyProgram.class.getResourceAsStream("/net/codejava/config/config.properties"); Properties props = new Properties(); props.load(inputStream);
NOTE: the methods load() or loadFromXML() do not close the reader nor the input stream, so you should close them afterward:
3. Getting properties values
-
- String getProperty(String key) : returns value of the property specified by the given key. It returns null if the key not found.
- String getProperty(String key, String defaultValue) : like the above method, but this method will return a default value if the key not found.
String host = props.getProperty("host");
String host = props.getProperty("host", "localhost");
NOTE: The method getProperty() searches in the current property list (loaded from the properties) file, then in the default properties list (if specified when constructing the Properties object).
4. Setting properties values
Object setProperty(String key, String value)
This method returns previous value of the property specified by the given key.
props.setProperty("host", "www.codejava.net");
NOTE: the method setProperty() does not update the properties file, it just updates the internal properties list.
5. Saving properties file
To save the properties into the file permanently, use the store() method for plain text file and storeToXML() method for XML file. And we have to supply either a java.io.Writer object or an OutputStream object to these methods and also a comment text. Following are some examples:
- Save to plain text file using a Writer object:
File configFile = new File("config.properties"); FileWriter writer = new FileWriter(configFile); props.store(writer, "host settings");
File configFile = new File("config.xml"); OutputStream outputStream = new FileOutputStream(configFile); props.storeToXML(outputStream, "host settings");
NOTE: the methods store() or storeToXML() do not close the writer nor the output stream, so you should close them explicitly:
6. Sample Swing application
On startup, the program will try to load properties from config.properties file. If the file has not existed before, it will use the default properties. When clicking on the Save button, the properties values will be stored in the config.properties file.
You can download the program’s source code and executable jar file in the attachments section.
Other Java Coding Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.