Dernière modification : 23/08/2022

Les fichiers de configuration - Les Properties avec Java

Les propriétés en Java sont des valeurs de configuration renseignées dans des applications Java. Un fichier de propriétés (.properties) est un fichier qui contient ces valeurs dans des paires clé-valeur.

Dans cet article nous allons voir comment utiliser les properties avec Java sans framework additionnel.

1. Chargement et lecture

1.1 Properties interne

Fichier application.properties :

mail=contact@laulem.com

Chargement du fichier application.properties :

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 Properties externe

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. Lecture de toutes les 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. Ecriture de 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();
}

Fichier application.properties généré :

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