Dernière modification : 14/07/2024

Configuration Files - Properties with Java

Properties in Java are configuration values specified in Java applications. A properties file (.properties) is a file that contains these values in key-value pairs.

In this article, we will see how to use properties with Java without any additional framework.

1. Loading and Reading

1.1 Internal Properties

File application.properties:

mail=contact@laulem.com

Loading the application.properties file:

try (InputStream input = App1.class.getClassLoader().getResourceAsStream("application.properties")) {
    Properties prop = new Properties();
    prop.load(input);
    System.out.println(prop.getProperty("mail")); // contact@laulem.com
} catch (IOException ex) {
    ex.printStackTrace();
}

1.2 External Properties

try (InputStream input = new FileInputStream("path/application.properties")) {
	Properties prop = new Properties();
    prop.load(input);
    System.out.println(prop.getProperty("mail"));
} catch (IOException ex) {
    ex.printStackTrace();
}

2. Reading All Properties

try (InputStream input = App1.class.getClassLoader().getResourceAsStream("application.properties")) {
	Properties prop = new Properties();
	prop.load(input);
	prop.forEach((key, value) -> System.out.println("Key : " + key + ", Value : " + value)); // Key : mail, Value : contact@laulem.com
} catch (IOException ex) {
	ex.printStackTrace();
}

3. Writing Properties

try (OutputStream output = new FileOutputStream("path/application.properties")) {
	Properties prop = new Properties();
	prop.setProperty("name", "alex");
	prop.setProperty("mail", "contact@laulem.com");
	prop.store(output, null);
} catch (IOException io) {
	io.printStackTrace();
}

Generated application.properties file:

#Wed Jan 13 16:48:55 CET 2021
mail=contact@laulem.com
name=alex

 

 

LauLem.com - (Pages in French) Conditions of Use - Legal Information - Cookie Policy - Personal Data Protection Policy - About