Java – Récupérer un fichier properties

CodeDevFrançais

Dans la série code à garder sous la main : récupérer un fichier properties en Java :

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*********************************************************/
/*            Récuperer un fichier properties            */
/*********************************************************/
 
import java.io.InputStream;
import java.util.Properties;
 
public class LoadProperties {
 
    private static Properties props = null;
    private static final String FICHIER_PROPERTIES = "com/mestests/ejb/client/agent.properties";
 
    // Singleton
    private static LoadProperties instance = new LoadProperties();
 
    public static LoadProperties getInstance() {
        return instance;
    }
 
    private LoadProperties() {
        this.init();
    }
 
    private void init() {
 
        // Si le fichier de properties n'est pas chargé : on le charge
        if (props == null) {
            try {
                InputStream is = LoadProperties.class.getResourceAsStream(FICHIER_PROPERTIES);
                if (is == null) {
                    throw  new Exception();
                }
                props = new Properties();
                props.load(is);
            }
            catch (Exception e) {
                System.out.println("Impossible de charger le fichier de configuration demandé !");
            }
        }
    }
 
    public String getProperty(String maClef) {
        return props.getProperty(maClef);
    }
}

Exemple de fichier properties:

Acces par:

1
String maValeur = LoadProperties.getInstance().getProperty("maclef");
Next
Java – Read a property file

Leave a comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.