Pages

How to load a configuration file in java from resources directory | java | maven

While writing a software, its quiet often phenomenon that we want to put some of our configurations in easily editable configuration files rather then hard-coding everything in the application itself. It reduces the overhead of compiling the code with every little changes. Often in the production environment, its not even feasible to change compile it.
Maven projects have a definite directory structure where the class files are in one directory and the resources relating to the class files are in another. While loading the properties object with a *.properties file, the input stream expects the file to be in the same directory. Naturally this leads to an error, if our properties file is in the resources/ directory.
Well, here's the code for how you do it.
location.properties
## location.properties

INDEX_DIR=url_index
TEST=text_parameter

Configuration.java
package com.gazecode.config;

import java.io.InputStream;
import java.util.Properties;

public class Configuration {
 private Properties properties = new Properties();

 public Configuration() {
  try {
   
//   System.out.println("Working Directory = " +
//                System.getProperty("user.dir"));
   properties.load(Configuration.class.getResourceAsStream("/location.properties"));
   
  } catch (Exception e) {
   System.out.println("Error while loading");
   e.printStackTrace();
  }
 }

 public String getProperty(String key) {
  return properties.getProperty(key);
 }

 public void setProperty(String key, String value) {
  properties.setProperty(key, value);
 }
 
 public static void main(String[] args) {
  System.out.println("Starting the process");
  Configuration config = new Configuration();
  System.out.println(config.getProperty("INDEX_DIR"));
  System.out.println(config.getProperty("TEST"));
 }
}

1 comment:

  1. They can also play a crucial role in content marketing strategies for businesses, driving traffic to websites and boosting online visibility. Nord VPN Offer While blogs may lack the rigorous fact-checking of articles, they provide a unique space for personal expression and storytelling.

    ReplyDelete

If you like to say anything (good/bad), Please do not hesitate...