Load a properties file from classpath

Category : Java | Sub Category : Read and Write (Input/Output ) a file | By Runner Dev Last updated: 2020-12-11 15:50:01 Viewed : 263


Load a properties file from classpath

1. Java properties file is used to store  configuration data 

database.properties

db.url=127.0.0.1

db.user=admin

db.password=Admin@123


·              project structure for testing



2.Example

   LoadPropertiesFile.java

 

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

public class LoadPropertiesFile {

	public static void main(String[] args) {

		/** Returns an input stream for reading the specified resource. **/
		try (InputStream input = LoadPropertiesFile.class.getClassLoader().getResourceAsStream("database.properties")) {

			/** Creates an empty property list with no default values. **/
			Properties prop = new Properties();

			if (input == null) {
				System.out.println("Unable to find database.properties");
				return;
			}

			/** Reads a property list (key and element pairs) from the input byte stream **/
			prop.load(input);

			/** Searches for the property with the specified key in property list */
			System.out.println(prop.getProperty("db.url"));
			System.out.println(prop.getProperty("db.user"));
			System.out.println(prop.getProperty("db.password"));

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

 

 Output:

   127.0.0.1

    admin

  Admin@123




Search
Related Articles

Leave a Comment: