How to load property file in java

Overview

Application mostly require a file to store the configuration or data oustide the complied code. Most commonly used method is to store in properties file in the form of key value pair. In the below example. we’ll see how to read those properties file using Java.

Java has in-built support in java.util.Properties class to perform read/write operations on the properties file.

Properties file

config.properties

1
2
name=tutorialflix
description=loading properties from file

Reading properties file from classpath or resources folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.tutorialflix.example.properties.file;

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

public class LoadPropertyFileFromClasspath {

public static void main(String[] args) {

try (InputStream input = LoadPropertyFileExample.class.getClassLoader().getResourceAsStream("config.properties")) {

Properties prop = new Properties();

// load a properties file
prop.load(input);

// get the property value and print it out
System.out.println(prop.getProperty("name"));
System.out.println(prop.getProperty("description"));

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

}

}

Reading properties file from disk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.tutorialflix.example.properties.file;

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

public class LoadPropertyFileFromPath {

public static void main(String[] args) {

try (InputStream input = new FileInputStream("path/to/config.properties")) {


Properties prop = new Properties();

// load a properties file
prop.load(input);

// get the property value and print it out
System.out.println(prop.getProperty("name"));
System.out.println(prop.getProperty("description"));

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

}

}
Author

Vaibhav Bhootna

Posted on

2019-04-24

Updated on

2020-10-31

Licensed under

Comments