javaclasspropertiesgetproperties

How to access java properties file


I have a properties file.

#My properties file
config1=first_config
config2=second_config
config3=third_config
config4=fourth_config

I have a class that loads the properties file in a small Java app. It works fine, specifically when I try to access each property within this class's method.

public class LoadProperties {
  public void loadProperties() {
    Properties prop = new Properties();
    InputStream input = null;
    try {
        input = new FileInputStream("resources/config.properties");
        prop.load(input);

    } catch (Exception e) {
        System.out.println(e);
    }
  }
}

I am calling that class's method in another class, in a method.

public class MyClass {
  public void myMethod() {
    LoadProperties lp = new LoadProperties();
    lp.loadProperties();
    /*..More code...*/
  }
}

How do I access the properties in the myMethod method in the MyClass class? I tried typing prop.getProperty("[property_name]"), which does not work.

Any ideas? I'm assuming that this would be how I would access the properties. I can store them in variables in the loadProperties class and return the variables, but I thought that I would be able to access them how I stated above.


Solution

  • You can change the LoadProperties class to load the properties and add a method to return the loaded properties.

    public class LoadProperties {
        Properties prop = new Properties();
        public LoadProperties() {
            try (FileInputStream fileInputStream = new FileInputStream("config.properties")){
                prop.load(fileInputStream);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    
        public Properties getProperties() {
            return prop;
        }
    }
    

    Then use it like this

    public class MyClass {
        public void myMethod() {
            LoadProperties loadProperties = new LoadProperties();
            System.out.println(loadProperties.getProperties().getProperty("config1"));
        }
    }