L'objectif est de définir des paramètres dans un fichier ini, par exemple :
[database]
DriverClass=org.hsqldb.jdbcDriver
url=jdbc:hsqldb:db/maBase
Username=sa
Password=
default_schema=PUBLIC
[appli]
;mode : prod|debug
mode=debug
;fenetre : normal|maximized
fenetre=normal
fenetre_largeur=1024
fenetre_hauteur=768
Le fichier de paramètres va être traité à partir de la classe téléchargée ici : ftp://ftp-developpez.com/java/sources/ProfileReader.zip, et modifiée pour tenir compte des variables vides (exemple : Password=). Voici la classe complète modifiée :
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.StringTokenizer;
/**
*
* @author ftp://ftp-developpez.com/java/sources/ProfileReader.zip
*
*/
public class ProfileReader {
private Hashtable<String, Hashtable<String, String>> _sections;
/**
* Creates a new ProfileReader
*/
public ProfileReader() {
_sections = new Hashtable<String, Hashtable<String, String>>();
}
/**
* Load the current objet with the data found in the given stream
*
* @param aStream
* the stream that represent the INI file.
* @throws Exception
* in case of problems.
*/
public void load(InputStream aStream) throws Exception {
if (null == aStream) {
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
aStream));
String line = null;
String sectionName = null;
Hashtable<String, String> section = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
// All the data should be in a section
if (null == sectionName) {
if ((!line.startsWith("[")) || (!line.endsWith("]"))) {
throw new Exception(
"Invalid format: data found outside section");
}
sectionName = line.substring(1, line.length() - 1).trim();
addSection(sectionName);
section = getSection(sectionName);
} else {
if (line.startsWith("[")) {
if (!line.endsWith("]")) {
throw new Exception(
"Invalid format: no ending ] for section name");
}
sectionName = line.substring(1, line.length() - 1).trim();
addSection(sectionName);
section = getSection(sectionName);
} else {
addLineToSection(line, section);
}
}
}
}
/**
* Return the value of the given key in the given section
*
* @param aSectionName
* the name of the section
* @param aKey
* the key
* @return the value if found or null.
*/
public String getProperty(String aSectionName, String aKey) {
Hashtable<String, String> section = getSection(aSectionName);
if (null == section) {
return null;
}
return (String) section.get(aKey);
}
private void addLineToSection(String aLine,
Hashtable<String, String> aSection) throws Exception {
if (null == aLine) {
return;
}
if (null == aSection) {
throw new Exception("No section found to add data");
}
aLine = aLine.trim();
// lines that starts with ; are comments
if (aLine.startsWith(";")) {
return;
}
// Avoid the empty lines
if (aLine.length() == 0) {
return;
}
if (aLine.endsWith("=")) {
}
// The format of a line of data is: key = value
StringTokenizer st = new StringTokenizer(aLine, "=");
String key = "";
String value = "";
// The value is empty
if (aLine.endsWith("=")) {
key = st.nextToken().trim();
} else {
// the value is defining
if (st.countTokens() != 2) {
throw new Exception("Invalid format of data: " + aLine);
}
key = st.nextToken().trim();
// a key should not contain spaces
for (int index = 0; index < key.length(); index++) {
if (Character.isWhitespace(key.charAt(index))) {
throw new Exception("Invalid format of data: " + aLine);
}
}
value = st.nextToken().trim();
}
aSection.put(key, value);
}
private void addSection(String aSectionName) {
if (null == aSectionName) {
return;
}
Hashtable<String, String> section = getSection(aSectionName);
if (null == section) {
section = new Hashtable<String, String>();
_sections.put(aSectionName, section);
}
}
private Hashtable<String, String> getSection(String aSectionName) {
return (Hashtable<String, String>) _sections.get(aSectionName);
}
}
Les paramètres sont lus ainsi :
import java.io.FileInputStream;
import java.io.InputStream;
/**
* @author quinton classe contenant les paramètres généraux de l'application
*/
public class Parametre {
public static String driverClass, url, username, password, default_schema,
mode, fenetre;
public static int fenetre_largeur, fenetre_hauteur;
/**
* Instanciation post-lecture des parametres
*/
public Parametre() {
}
/**
* Première instanciation pour lecture des paramètres
*
* @param String
* nomFichierParam
*/
public Parametre(String nomFichierParam) {
ProfileReader pr = new ProfileReader();
try {
InputStream inputStream = new FileInputStream(nomFichierParam);
try {
pr.load(inputStream);
} catch (Exception e) {
System.err.println("Impossible de lire le fichier "
+ nomFichierParam);
System.err.println(e.getMessage());
}
/*
* Lecture des parametres
*/
try {
driverClass = pr.getProperty("database", "DriverClass");
url = pr.getProperty("database", "url");
username = pr.getProperty("database", "Username");
password = pr.getProperty("database", "Password");
default_schema = pr.getProperty("database", "default_schema");
mode = pr.getProperty("appli", "mode");
fenetre = pr.getProperty("appli", "fenetre");
try {
fenetre_largeur = Integer.parseInt(pr.getProperty("appli", "fenetre_largeur"));
} catch (Exception e) {
fenetre_largeur = 800;
}
try {
fenetre_hauteur = Integer.parseInt(pr.getProperty("appli", "fenetre_hauteur"));
} catch (Exception e) {
fenetre_hauteur = 600;
}
} catch (Exception e) {
System.err
.println("Impossible d'initialiser correctement la classe ProfileReader");
}
} catch (Exception e) {
System.err
.println("Impossible d'ouvrir ou de trouver le fichier de paramètres "
+ nomFichierParam);
}
}
}
et utilisés ainsi, dans l'application :
String nomFichierParam="param/param.ini";
new Parametre(nomFichierParam);
[...]
fenetre.setSize(Parametre.fenetre_largeur, Parametre.fenetre_hauteur);