Read config files in java

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.

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);

Читайте также:  What is mock object in java

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

Источник

Java Properties File: How to Read config.properties Values in Java?

.properties is a file extension for files mainly used in Java related technologies to store the configurable parameters of an application. They can also be used for storing strings for Internationalization and localization; these are known as Property Resource Bundles.

Each parameter is stored as a pair of strings, one storing the name of the parameter (called the key/map ), and the other storing the value.

Below is a sample Java program which demonstrate you how to retrieve/read config.properties values in Java. For update follow this tutorial.

We will create 3 files:

  1. CrunchifyReadConfigMain.java
  2. CrunchifyGetPropertyValues.java
  3. config.properties file

Main Class (CrunchifyReadConfigMain.java) which will call getPropValues() method from class CrunchifyGetPropertyValues.java .

Let’s get started:

Step-1: Create config.properties file.

  1. Create Folder “ resources ” under Java Resources folder if your project doesn’t have it.
  2. create config.properties file with below value.

How to read config.properties in Java - Crunchify Tips

/Java Resources/config.properties file content:

#Crunchify Properties user=Crunchify company1=Google company2=eBay company3=Yahoo

Step-2

Create file CrunchifyReadConfigMain.java

package crunchify.com.tutorial; import java.io.IOException; /** * @author Crunchify.com * */ public class CrunchifyReadConfigMain < public static void main(String[] args) throws IOException < CrunchifyGetPropertyValues properties = new CrunchifyGetPropertyValues(); properties.getPropValues(); >>

Step-3

Create file CrunchifyGetPropertyValues.java

package crunchify.com.tutorial; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Properties; /** * @author Crunchify.com * */ public class CrunchifyGetPropertyValues < String result = ""; InputStream inputStream; public String getPropValues() throws IOException < try < Properties prop = new Properties(); String propFileName = "config.properties"; inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) < prop.load(inputStream); >else < throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); >Date time = new Date(System.currentTimeMillis()); // get the property value and print it out String user = prop.getProperty("user"); String company1 = prop.getProperty("company1"); String company2 = prop.getProperty("company2"); String company3 = prop.getProperty("company3"); result = "Company List = " + company1 + ", " + company2 + ", " + company3; System.out.println(result + "\nProgram Ran on " + time + " by user=" + user); > catch (Exception e) < System.out.println("Exception: " + e); >finally < inputStream.close(); >return result; > >

Step-4

Run CrunchifyReadConfigMain and checkout result.

Company List = Google, eBay, Yahoo Program Ran on Mon May 13 21:54:55 PDT 2013 by user=Crunchify

As usually happy coding and enjoy. Do let me know if you see any exception. List of all Java Tutorials.

Are you running above program in IntelliJ IDE and getting NullPointerException?

Please follow below tutorial for fix.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Suggested Articles.

Источник

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:

config properties fileconfig XML file

.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

    config properties demo program

    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.

    Источник

Оцените статью