FreeKB - Obtain data from a properties file in Eclipse
Obtain data from a properties file in Eclipse

Home > Search


Let's say you have a file named example.properties that contains the following markup.

greeting=Hello World

 

You can then create a class that gets the value from the properties file. Notice in this example that the the full path to the example.properties file is used. In this example, the example.properties file resides on the same system as Eclipse. The "greeting" key is obtained from example.properties, which will return a value of Hello World.

package com.example.main;

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

public class Hello {	
    Properties prop = new Properties();
    public String greeting;

    public Hello() {
        try {
            InputStream fis = new FileInputStream("/opt/properties/example.properties");
            prop.load(fis);
			
            greeting = prop.getProperty("greeting");

            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        } 
    } 

    // this is used to create a string object that can be used in a JSP page
    public String getGreeting(){
        return greeting;
    }
}

 

The class is now ready to be used. In the example above, the "Hello" class is in the "com.sample.main" package, so we first import "com.sample.main.Hello". The, create a new object (foo in this example). In Hello foo = new Hello();, the text "Hello" must be used since the class is named "Hello". Using foo, get the value of the greeting variable. Be careful to use "out.print" and not "out.println". 

<%@page import="com.sample.main.Hello"%>

<%
  Hello foo = new Hello();
  out.print(foo.getGreeting());
%>

 

Navagiating to the JSP page should now display the value associated with the "greeting" key in the properties file, which is "Hello World" in this example..

 

It is noteworthy that instead of using a properties file, if the app is being deployed to WebSphere, WebSphere variables could be used instead.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter dd7f7 in the box below so that we can be sure you are a human.




Comments