Java Properties File

  1. Home
  2. Blog
  3. Java Properties File

Java Properties File

To store come configurable attributes of an application, we sometime use .properties files. Also know as Property Resource Bundles can be used to store strings for Internationalization.It’s like storing parameters as key value pairs. Let’s see an example here.

First we will create a java project, let’s name it as “javaProperties” and added few classes to it with one properties file.

javaprop

FetchRequiredProperties.java reads the required.properties file from the classpath and passes it to ReadRequiredProperties

package javaProperties;

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

public class FetchRequiredProperties {
  String props = "";
  InputStream inputStream;
 
  public String getPropValues() throws IOException {
 
    try {
      // Create properties object
      Properties prop = new Properties();
      // Name of the file were to read the data
      String propFileName = "required.properties";
      inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
      
      // If we got the resource load it
      if (inputStream != null) {
        prop.load(inputStream);
      } else {
        throw new FileNotFoundException("property file '" + propFileName + "' not found");
      }
 
      // get properties
      String requiredProps = prop.getProperty("displayProp");
      props = requiredProps;
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    } finally {
      inputStream.close();
    }
    return props;
  }
}

ReadRequiredProperties.java we are calling FetchRequiredProperties method getPropValues and writing the output to console.

package javaProperties;

import java.io.IOException;

public class ReadRequiredProperties {

  public static void main(String[] args) throws IOException {
    FetchRequiredProperties properties = new FetchRequiredProperties();
    String requiredProps = properties.getPropValues();
    System.out.println("requiredProps: "+requiredProps);
  }
}

required.properties is where we stored our required properties.

displayProp=name,label,img,brand,material

HTH Cheers

Let's Share

Comment (1)

Comments are closed.

Show Buttons
Hide Buttons