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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import java.io.*;
import java.util.Properties;
public class MyProperties {
// Constante
private final static String PROPERTIES_PATH = System.getProperty("user.dir") + "/myapp.properties";
// Singleton
private static MyProperties instance = null;
// Attribut
private Properties prop = null;
// Constructeur
private MyProperties(){
prop = new Properties();
// Si le fichier n'existe pas, on le crée
if(!new File(PROPERTIES_PATH).exists()){
save();
}
// lecture des proprietes
read();
}
// récupération de l'instance
public static MyProperties getInstance(){
// Si l'instance n'existe pas, on la crée
if(instance==null)instance = new MyProperties();
return instance;
}
// Lecture/Ecriture des proprietes
private void save(){
try {
FileOutputStream out = new FileOutputStream(PROPERTIES_PATH);
prop.store(out, null);
out.flush();
out.close();
} catch (IOException e) {e.printStackTrace();}
}
private void read(){
try{
FileInputStream in = new FileInputStream(PROPERTIES_PATH);
prop.load(in);
in.close();
}catch(Exception e){e.printStackTrace();}
}
// Ajout/Récupération des proprietes
public void add(String key, String value){
prop.setProperty(key, value);
save();
}
public String get(String key){
return (String)prop.get(key);
}
} |