Complément pour tenir compte des lignes sans valeur
Bonjour,
Dans un fichier ini, il est fréquent de ne pas renseigner de valeurs (mot de passe, par exemple, s'il n'est pas utilisé - cas d'une base de données embarquée).
Voici la correction qui permet de gérer correctement ce cas de figure :
[
Code:
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
| 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);
} |