In this post, we will learn how to load property file in java. Properties file is used to store and retrieve values from file.
It is stored as key and value pair. Below is an sample property file
database.properties
database.url=jdbc:mysql://localhost:3306/beginnersbug
database.username=root
database.password=password
Read properties from absolute path
import java.io.FileReader;
import java.util.Properties;
public class LoadProperty {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("D:\\BB\\Workspace\\database.properties");
Properties p = new Properties();
p.load(reader);
System.out.println(p.getProperty("database.url"));
System.out.println(p.getProperty("database.username"));
System.out.println(p.getProperty("database.password"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
jdbc:mysql://localhost:3306/beginnersbug
root
password
Read properties from class path
Please make sure you have database.properties in class path. else you will get Please check the file present in classpath
Syntax
LoadPropertyFromClassPath.class.getResourceAsStream("database.properties");
import java.io.InputStream;
import java.util.Properties;
public class LoadPropertyFromClassPath {
public static void main(String[] args) {
try {
Properties prop = new Properties();
InputStream stream = LoadPropertyFromClassPath.class.getResourceAsStream("database.properties");
if (stream != null) {
prop.load(stream);
System.out.println(prop.getProperty("database.url"));
System.out.println(prop.getProperty("database.username"));
System.out.println(prop.getProperty("database.password"));
} else {
System.err.println("Please check the file present in classpath");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
jdbc:mysql://localhost:3306/beginnersbug
root
password
Print all the values from property file
Syntax
prop.keySet().stream().map(key -> key + ": " + prop.getProperty(key.toString()))
.forEach(System.out::println);
Example
import java.io.InputStream;
import java.util.Properties;
public class PrintPropertis {
public static void main(String[] args) {
try {
Properties prop = new Properties();
InputStream stream = LoadPropertyFromClassPath.class.getResourceAsStream("database.properties");
if (stream != null) {
prop.load(stream);
prop.keySet().stream().map(key -> key + ": " + prop.getProperty(key.toString()))
.forEach(System.out::println);
} else {
System.err.println("Please check the file present in classpath");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
database.password: password
database.url: jdbc:mysql://localhost:3306/beginnersbug
database.username: root
Github
Related Articles
how to read a file from java with example
delete a file from java code