How to Load Properties File From Classpath in Java


In this example we will show how to load properties file from the classpath in Java.

Source Code

package com.beginner.examples;

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

public class LoadPropertiesFileFromClasspath {

	public static void main(String[] args) {
		
		/*
		 * Use FileInputStream to load the properties file from classpath.
		 */
		InputStream inputStream = null;
		Properties properties = null;
		try {
			properties = new Properties();
		File file = new File("tmp.properties");
		inputStream = new FileInputStream(file);
		properties.load(inputStream);
		System.out.println("db.username: " + properties.getProperty("db.username"));
		System.out.println("db.userage: " + properties.getProperty("db.userage"));
        } catch (FileNotFoundException e) {
		e.printStackTrace();
        } catch (IOException e) {
		e.printStackTrace();
        }
		
		

	}

}

tmp.properties:

db.username = Alice
db.userage = 17

Output:

db.username: Alice
db.userage: 17

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments