Bootstrap FreeKB - Java - Obtain data from a properties file
Java - Obtain data from a properties file

Updated:   |  Java articles

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

greeting=Hello World

 

Here is an example Java class that would get the value of the greeting key (Hello World) from the example.properties file. In this example that the the full path to the example.properties file is used and the example.properties file resides on the same system as the Java application.

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

public class Main {
	public static void main(String[] args) throws IOException {
	    
        InputStream file = new FileInputStream("C:\\Users\\john.doe\\example.properties");
        Properties prop = new Properties();
        prop.load(file);
        String greeting = prop.getProperty("greeting");
        file.close();

        System.out.println("greeting = " + greeting);

	}
}

 

Or, like this.

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 file = new FileInputStream("/opt/properties/example.properties");
            prop.load(file);
			
            greeting = prop.getProperty("greeting");

            file.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;
    }
}

 

You could then add the following to line 1 of the JSP file. This is the combination of the package (com.sample.main) and the class (Hello.java).

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

 

And then add the following inside the <body> tags of the JSP file.

  • In this example, "Hello" must be used because the name of the class in Hello.java is Hello.
  • In this example, "getGreeting" must be used because the name of the method in Hello.java is getGreeting. Be careful to use "out.print" and not "out.println". 
<body>
<%
  Hello foo = new Hello();
  out.print(foo.getGreeting());
%>
</body>

 

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..

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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