Reading properties files in java

How to read Properties File in Java – XML and Text Example Tutorial

Reading and writing properties file in Java is a little different than reading or writing text file in Java or reading xml files in Java using xml parsers like DOM because Java provides the special provision to the properties file. For those who are not familiar with Properties files in java, It is used to represent configuration values like JDBC connectivity parameter or user preference settings and has been a primary source of injecting configuration on Java applications. Properties file in Java is a text file that stores data in the form of key and value, key being known as property. Java allows you to read the value of the property by providing its name which makes it easy to access configuration settings. Many application like Spring and Spring Boot also uses property file for configurations for example application.properties is commonly used to setup Spring boot.

Two more popular examples of properties file are jdbc.properties often used to store database connection settings like URL, username, and password, and log4j.properties file which settings for java logging using log4j.

There are also many frameworks that use Java properties files like Struts , Spring , Displaytag, etc. Another advantage of using properties files is that you can represent data either in xml format or in properties format. xml format will be particularly useful if you are sharing configuration or settings with some external tool that understands only XML.

In this article, we will see how to read and write into Properties files in Java in both xml and text format.

And, If you are new to Java Programming then I also recommend you go through these Java online courses on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.

Reading values from Java Properties File

example of How to read Properties File in Java – XML and Text format

Here is a sample code example of reading a properties file in Java. In this example, we will read a property from jdbc.properties file which contains database connection settings, you might have already used that.

Читайте также:  Java null types sql

Anyway, it contains username, password, and jdbc driver class name as a key-value format. We will read these values from the Java program using java.util.Properties class which represents properties file in Java program.

Code Examples of Reading Properties File in Java

import java.io.FileInputStream ;
import java.io.FileNotFoundException ;
import java.io.IOException ;
import java.util.Properties ;

public class PropertyFileReader

public static void main ( String args []) throws FileNotFoundException, IOException

//Reading properties file in Java example
Properties props = new Properties () ;
FileInputStream fis = new FileInputStream ( «c:/jdbc.properties» ) ;

//loading properties from a property file
props. load ( fis ) ;

//reading property
String username = props. getProperty ( «jdbc.username» ) ;
String driver = props. getProperty ( «jdbc.driver» ) ;
System. out . println ( «jdbc.username: » + username ) ;
System. out . println ( «jdbc.driver: » + driver ) ;

Output:
jdbc. username : test
jdbc. driver : com. mysql . jdbc .Driver

If you read any property which is not specified in the properties file then you will props.getProperty() will return null .

Now let’s see another example of reading property files from xml format. as you know properties file in java can be represented in xml format and Java provides a convenient method called loadFromXML() to load properties from xml file. here is a quick example of parsing xml properties file and reading data.

How to Read Property file in XML format – Java

In the earlier section, we have seen a sample working code example of reading properties file (.properties) but as I said earlier you can also define property in xml format this method is also very popular among various Java logging frameworks e.g. log4j, and also among others.

In this section, we will see how to read property file which is written in xml format. If you see the code not many changes instead of Properties. load() we are using Properties.loadFromXML() and then the rest of the stuff of getting property and printing its value is the same as in the last example.

By the way here is our sample java properties file in xml format, which defined two entries with key jdbc.username and jdbc.password.

public static void main ( String args []) throws FileNotFoundException, IOException

//Reading properties file in Java example
Properties props = new Properties () ;
FileInputStream fis = new FileInputStream ( «c:/properties.xml» ) ;

//loading properties from properties file
props. loadFromXML ( fis ) ;

//reading property
String username = props. getProperty ( «jdbc.username» ) ;
System. out . println ( «jdbc.username: » + username ) ;

output:
jdbc. username : root

We have seen how to read properties files in java, In both text and xml format. Properties file are immensely helpful for providing settings and configuration data to any Java program. Text properties file can only represent linear values but xml properties file can also represent hierarchical values which makes Properties file preferred choice in logging frameworks.

Читайте также:  Градиентный текст

Источник

Java Read and Write Properties File Example

In this Java tutorial, learn to read properties file using Properties.load() method. Also we will use Properties.setProperty() method to write a new property into the .properties file.

Given below is a property file that we will use in our example.

firstName=Lokesh lastName=Gupta blog=howtodoinjava technology=java

2. Reading Properties File

In most applications, the properties file is loaded during the application startup and is cached for future references. Whenever we need to get a property value by its key, we will refer to the properties cache and get the value from it.

The properties cache is usually a singleton static instance so that application does not require to read the property file multiple times; because the IO cost of reading the file again is very high for any time-critical application.

Example 1: Reading a .properties file in Java

In the given example, we are reading the properties from a file app.properties which is in the classpath. The class PropertiesCache acts as a cache for loaded properties.

The file loads the properties lazily, but only once.

import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; public class PropertiesCache < private final Properties configProp = new Properties(); private PropertiesCache() < //Private constructor to restrict new instances InputStream in = this.getClass().getClassLoader().getResourceAsStream("application.properties"); System.out.println("Reading all properties from the file"); try < configProp.load(in); >catch (IOException e) < e.printStackTrace(); >> //Bill Pugh Solution for singleton pattern private static class LazyHolder < private static final PropertiesCache INSTANCE = new PropertiesCache(); >public static PropertiesCache getInstance() < return LazyHolder.INSTANCE; >public String getProperty(String key) < return configProp.getProperty(key); >public Set getAllPropertyNames() < return configProp.stringPropertyNames(); >public boolean containsKey(String key) < return configProp.containsKey(key); >>

In the above code, we have used Bill Pugh technique for creating a singleton instance.

public static void main(String[] args) < //Get individual properties System.out.println(PropertiesCache.getInstance().getProperty("firstName")); System.out.println(PropertiesCache.getInstance().getProperty("lastName")); //All property names System.out.println(PropertiesCache.getInstance().getAllPropertyNames()); >
Read all properties from file Lokesh Gupta [lastName, technology, firstName, blog]

3. Writing into the Property File

Personally, I do not find any good reason for modifying a property file from the application code. Only time, it may make sense if you are preparing data for exporting to third party vendor/ or application that needs data in this format only.

Example 2: Java program to write a new key-value pair in properties file

So, if you are facing similar situation then create two more methods in PropertiesCache.java like this:

public void setProperty(String key, String value) < configProp.setProperty(key, value); >public void flush() throws FileNotFoundException, IOException < try (final OutputStream outputstream = new FileOutputStream("application.properties");) < configProp.store(outputstream,"File Updated"); outputstream.close(); >>
  • Use the setProperty(k, v) method to write new property to the properties file.
  • Use the flush() method to write the updated properties back into the application.properties file.
PropertiesCache cache = PropertiesCache.getInstance(); if(cache.containsKey("country") == false) < cache.setProperty("country", "INDIA"); >//Verify property System.out.println(cache.getProperty("country")); //Write to the file PropertiesCache.getInstance().flush();
Reading all properties from the file INDIA

And the updated properties file is:

#File Updated #Fri Aug 14 16:14:33 IST 2020 firstName=Lokesh lastName=Gupta technology=java blog=howtodoinjava country=INDIA

That’s all for this simple and easy tutorial related to reading and writing property files using java.

Читайте также:  Css кликать сквозь элемент

Источник

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.

Источник

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