Sunday, December 16, 2018

Java Properties : How to Read/Write properties file in Java?

A .properties file is a simple collection of key-value pairs that can be parsed by the java.util.Properties class. Properties files are widely used for many purposes in all kinds of Java/j2ee applications, often to store configuration or localization data. And all over the project scripts can then use those properties easily.

There are a numerous ways to manipulate properties file in Java, in this post I’ll be covering the following topics with the code examples.
  1. Reading properties file from the Class Path
  2. Reading properties file from the file system
  3. Writing/Modifying properties file

    Create a properties file and place it in project directory.
    config.properties
    dburl=jdbc:oracle:thin:@127.0.0.0:1521:mycart
    dbuser=mycart_user
    dbpassword=Password@69
    

    1. Reading properties file from the Class Path

    Note: The java.lang.ClassLoader.getResourceAsStream() method returns an input stream for reading the specified resource..
    One way to read properties file in Java is to load it from the file system.

    Project Structure

     


    ClassPathProperties.java
    package com.rmpk.prj;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.util.Properties;
    import java.util.logging.Logger;
    
    public class ClassPathProperties {
     private static final Logger LOGGER = 
       Logger.getLogger(ClassPathProperties.class.getName());
    
     public ClassPathProperties() {
      loadProperties();
     }
    
     private Properties loadProperties() {
      Properties prop = new Properties();
      InputStream input = null;
      try {
       // Properties file read from outside class path
       String filePath = "config.properties";
    
       // load the file handle for class path
       input = this.getClass().getClassLoader().getResourceAsStream(filePath);
    
       // load a properties file
       prop.load(input);
    
       // Read earch properties by key
       String dburl = prop.getProperty("dburl");
       String dbpassword = prop.getProperty("dbpassword");
       String dbuser = prop.getProperty("dbuser");
       LOGGER.info(MessageFormat.format("dburl : {0}, dbpassword : {1}, "
         + "dbuser : {2}", dburl, dbpassword, dbuser));
    
       // Print properties in java 8
       prop.forEach((key, val) -> {
        LOGGER.info(MessageFormat.format("Key : {0}, Value : {1}", key, val));
       });
      } catch (Exception e) {
       e.printStackTrace();
       LOGGER.warning(e.getCause().getMessage());
      } finally {
       if (input != null) {
        try {
         input.close();
        } catch (IOException e) {
         e.printStackTrace();
         LOGGER.warning("loadProperties method IOException: " + 
           e.getCause().getMessage());
        }
       }
      }
      return prop;
     }
    
     public static void main(String[] args) {
      ClassPathProperties p = new ClassPathProperties();
     }
    }
    


    The output of the preceding code is as follows:


    2. Reading properties file from the file system 

    Note: A property list can contain another property list as its "defaults"; this second property list is searched if the property key is not found in the original property list. .
    If you have properties file in the project classpath then you can load it by using the getResourceAsStream method. That is another way to read properties file in Java.  

    Project Structure



    FileSystemProperties.java

    package com.rmpk.proj;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.text.MessageFormat;
    import java.util.Properties;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class FileSystemProperties {
    
     private static final Logger LOGGER = 
       Logger.getLogger(FileSystemProperties.class.getName());
    
     private static Properties loadProperties() {
      Properties prop = new Properties();
      FileInputStream input = null;
      try {
       // Properties file read from outside class path
       // String filePath = "resources/config.properties";
       String filePath = "config.properties";
    
       // load the file handle for main.properties
       input = new FileInputStream(filePath);
    
       // load a properties file
       prop.load(input);
    
       // Read earch properties by key
       String dburl = prop.getProperty("dburl");
       String dbpassword = prop.getProperty("dbpassword");
       String dbuser = prop.getProperty("dbuser");
       LOGGER.info(MessageFormat.format("dburl : {0}, dbpassword : {1}, "
         + "dbuser : {2}", dburl, dbpassword, dbuser));
    
       // Print properties in java 8
       prop.forEach((key, val) -> {
        LOGGER.info(MessageFormat.format("Key : {0}, Value : {1}", key, val));
       });
    
      } catch (Exception e) {
       e.printStackTrace();
       LOGGER.warning(e.getCause().getMessage());
      } finally {
       if (input != null) {
        try {
         input.close();
        } catch (IOException e) {
         e.printStackTrace();
         LOGGER.warning("loadProperties method IOException: " + 
           e.getCause().getMessage());
        }
       }
      }
      return prop;
     }
    
     public static void main(String[] args) {
      LOGGER.setLevel(Level.ALL);
      loadProperties();
     }
    }
    

    The output of the preceding code is as follows:


    Conclusion

    References