IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Collection et Stream Java Discussion :

Comment modifier une propriété d'un fichier de propriétés?


Sujet :

Collection et Stream Java

  1. #1
    Membre expérimenté
    Avatar de azerr
    Homme Profil pro
    Ingénieur Etude JEE/Eclipse RCP
    Inscrit en
    Avril 2006
    Messages
    942
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : France, Drôme (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur Etude JEE/Eclipse RCP
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Avril 2006
    Messages : 942
    Points : 1 464
    Points
    1 464
    Par défaut Comment modifier une propriété d'un fichier de propriétés?
    Bonjour,
    je developpe Akrogen http://akrogen.sourceforge.net/fr/index.html un plugin Eclipse de generation de code qui permet de decrire ses Wizard page en XML/XUL.

    J'aimerais ajouter la fonctionnalité de modification d'un fichier de propriete (on pourra ensuite ecrire en XUL/XML son Wizard page qui est mappe à un fichier de propriete pour avoir une interface convivial (onglets, combo,...) pour mettre à jour un fichier de propriétés).

    L'objet JAVA Properties permet de modifier un fichier de propriétés, cepandant il ne conserve pas les commentaires, les indentations, les espaces,...du fichier de propriété.

    Par exemple je souhaiterai modifier la propriété a du fichier de propriété
    avec la valeur NEW value :

    Le fichier de propriété :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    # First comment
     
     
    a=value A
    ################
    b = value B
    Le code JAVA qui modifie la proprété :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    Properties properties = new Properties();
    properties.load(TestPropertiesUpdate.class.getResourceAsStream("test.properties"));	String a = properties.getProperty("a");		
    properties.setProperty("a", "NEW value");		
    properties.store(System.out, "#Comment");
    En sortie j'obtiens :

    ##Comment
    #Thu May 03 13:37:41 CEST 2007
    b=value B
    a=NEW value
    ma propriété a bien été modifié mais il a perdu tous les commentaires, les espaces du fichie, l'ordre de la propriété...

    D'où ma question, existe-t-il une API qui permettent de gérer la modification d'un fichier de propriété tout en conservant les espaces, commentaires?

    Ce que j'aimerais éviter (mais j'ai bien peur qu'il va falloir que je m'y colle), c'est de développer ma propre mise à jour de fichier (on itère chaque ligne, on test si c'est une propriété, si ca en est une, on modifie la ligne...)

    Je vous remercie de votre aide

    Angelo

  2. #2
    Membre expérimenté
    Avatar de azerr
    Homme Profil pro
    Ingénieur Etude JEE/Eclipse RCP
    Inscrit en
    Avril 2006
    Messages
    942
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : France, Drôme (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur Etude JEE/Eclipse RCP
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Avril 2006
    Messages : 942
    Points : 1 464
    Points
    1 464
    Par défaut Classe ExtendedProperties pour mettre à jour fichier propriétés
    Bonjour,
    n'ayant rien trouve sur le net, je me suis mis à la tache du developpement de la classe ExtendedProperties qui permet de garder la structure du fichier de propriétés (conserve les commentaires, conserve l'ordre d'apparition des propriétés, conserve les retours à la ligne (a peu de chose près)) après modification (ajout de propriétés, modification de propriétés) d'un fichier de propriétés.

    Cette classe sera integre a Akrogen http://akrogen.sourceforge.net/fr/index.html plugin Eclipse de generation de code qui permettra de modifier un fichier de propriete à partir d'un Wizard page Eclipse decrit en XML/XUL (voir site Akrogen)

    Je vous mets en copie la classe que j'ai codé. Si vous etes interesses par le code, que vous trouvez des bugs, n'hesitez pas a me contacter.

    Voici le test effectue :

    fichier de propriété data.properties :

    ####### fields properties
    myform.myfield1.text=My field 1


    myform.myfield2.text=My field 2

    #


    ######
    Utilisation de ExtendedProperties
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
     
     
    // Load data.properties properties file
    ExtendedProperties properties = new ExtendedProperties();
    properties.load(ExtendedPropertiesTestCase.class
    		.getResourceAsStream("data.properties"));
     
    // Update myform.myfield1.text property
    String key = "myform.myfield1.text";
    String newValue = "New value for property 1.";
    properties.setProperty(key, newValue);
     
    String key1 = "myform.myNewField.text";
    String newValue1 = "Value for myNewField.";
    properties.setProperty(key1, newValue1);
     
    // Display properties file updated 
    properties.store(System.out, null);
    Resultat du test :

    ####### fields properties
    myform.myfield1.text=New value for property 1.


    myform.myfield2.text=My field 2

    #


    ######
    myform.myNewField.text=Value for myNewField.
    Voici les sources de ExtendedProperties :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
     
    package net.sourceforge.akrogen.core.internal.code.properties;
     
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Properties;
     
    /**
     * Extend java.util.Poperties to keep structure properties file
     * (comments, order of property,...) when properties file is
     * modifiy and saved.
     * 
     * @version 1.0.3
     * @author <a href="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
     * 
     */
    public class ExtendedProperties extends Properties {
     
    	private static final long serialVersionUID = 1L;
     
    	private final static String NEW_LINE = "\r\n";
     
    	/**
             * List which contains properties file content. This list contains :
             * <ul>
             * <li>String element which is the property key</li>
             * <li>StringBuffer which contains another character (comments, space..)</li>
             * </ul>
             */
    	private List contents;
     
    	public ExtendedProperties() {
    		contents = new ArrayList();
    	}
     
    	/**
             * Load properties stream by caching structure of properties file structure
             * (comments, property order)
             * 
             * @param inputStream
             *            properties stream
             * @exception IOException
             */
    	public void load(InputStream inputStream) throws IOException {
    		// The spec says that the file must be encoded using ISO-8859-1.
    		BufferedReader reader = new BufferedReader(new InputStreamReader(
    				inputStream, "ISO-8859-1"));
    		String line;
    		StringBuffer contentToAdd = null;
    		boolean lineWasAdded = false;
    		while ((line = reader.readLine()) != null) {
    			if (lineWasAdded) {
    				// Line was added, add new line string
    				addContent(NEW_LINE);
    				lineWasAdded = false;
    			}
    			char c = 0;
    			int pos = 0;
    			// Leading whitespaces must be deleted first.
    			while (pos < line.length()
    					&& Character.isWhitespace(c = line.charAt(pos))) {
    				// Character is whitespace
    				// Store into tempory StringBuffer content to add
    				if (contentToAdd == null)
    					contentToAdd = new StringBuffer();
    				contentToAdd.append(c);
    				pos++;
    			}
    			// If empty line or begins with a comment character, skip this
    			// line.
    			if ((line.length() - pos) == 0 || line.charAt(pos) == '#'
    					|| line.charAt(pos) == '!') {
    				// empty line or comment characters
    				// Store into tempory StringBuffer content to add
    				if (contentToAdd == null)
    					contentToAdd = new StringBuffer();
    				String content = line.substring(pos, line.length());
    				if (content != null && content.length() > 0) {
    					// Line is not empty, add content line
    					contentToAdd.append(content);
    				}
    				if (contentToAdd.toString().length() > 0)
    					// Content to add is not empty, add it
    					addContent(contentToAdd);
    				contentToAdd = null;
    				// new line String will be add on the next iteration
    				lineWasAdded = true;
    				continue;
    			}
    			// The characters up to the next Whitespace, ':', or '='
    			// describe the key. But look for escape sequences.
    			StringBuffer key = new StringBuffer();
    			while (pos < line.length()
    					&& !Character.isWhitespace(c = line.charAt(pos++))
    					&& c != '=' && c != ':') {
    				if (c == '\\') {
    					if (pos == line.length()) {
    						// The line continues on the next line. If there
    						// is no next line, just treat it as a key with an
    						// empty value.
    						line = reader.readLine();
    						if (line == null)
    							line = "";
    						pos = 0;
    						while (pos < line.length()
    								&& Character.isWhitespace(c = line.charAt(pos)))
    							pos++;
    					} else {
    						c = line.charAt(pos++);
    						switch (c) {
    						case 'n':
    							key.append('\n');
    							break;
    						case 't':
    							key.append('\t');
    							break;
    						case 'r':
    							key.append('\r');
    							break;
    						case 'u':
    							if (pos + 4 <= line.length()) {
    								char uni = (char) Integer.parseInt(line
    										.substring(pos, pos + 4), 16);
    								key.append(uni);
    								pos += 4;
    							} // else throw exception?
    							break;
    						default:
    							key.append(c);
    							break;
    						}
    					}
    				} else
    					key.append(c);
    			}
     
    			boolean isDelim = (c == ':' || c == '=');
    			while (pos < line.length()
    					&& Character.isWhitespace(c = line.charAt(pos)))
    				pos++;
     
    			if (!isDelim && (c == ':' || c == '=')) {
    				pos++;
    				while (pos < line.length()
    						&& Character.isWhitespace(c = line.charAt(pos)))
    					pos++;
    			}
     
    			StringBuffer element = new StringBuffer(line.length() - pos);
    			while (pos < line.length()) {
    				c = line.charAt(pos++);
    				if (c == '\\') {
    					if (pos == line.length()) {
    						// The line continues on the next line.
    						line = reader.readLine();
     
    						// We might have seen a backslash at the end of
    						// the file. The JDK ignores the backslash in
    						// this case, so we follow for compatibility.
    						if (line == null)
    							break;
     
    						pos = 0;
    						while (pos < line.length()
    								&& Character.isWhitespace(c = line.charAt(pos)))
    							pos++;
    						element.ensureCapacity(line.length() - pos
    								+ element.length());
    					} else {
    						c = line.charAt(pos++);
    						switch (c) {
    						case 'n':
    							element.append('\n');
    							break;
    						case 't':
    							element.append('\t');
    							break;
    						case 'r':
    							element.append('\r');
    							break;
    						case 'u':
    							if (pos + 4 <= line.length()) {
    								char uni = (char) Integer.parseInt(line
    										.substring(pos, pos + 4), 16);
    								element.append(uni);
    								pos += 4;
    							} // else throw exception?
    							break;
    						default:
    							element.append(c);
    							break;
    						}
    					}
    				} else
    					element.append(c);
    			}
    			put(key.toString(), element.toString());
    			addPropertKey(key.toString());
    			lineWasAdded = true;
    		}
    	}
     
    	public synchronized Object setProperty(String key, String value) {
    		if (get(key) == null) {
    			addContent("\r\n");
    			addPropertKey(key);
    		}
    		return put(key, value);
    	}
     
    	public synchronized void store(OutputStream out, String comments)
    			throws IOException {
    		// The spec says that the file must be encoded using ISO-8859-1.
    		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out,
    				"ISO-8859-1"));
    		store(writer, comments);
    	}
     
    	public synchronized void store(Writer writer, String comments)
    			throws IOException {
    		StringBuffer s = new StringBuffer(); // Reuse the same buffer.
    		for (Iterator iter = contents.iterator(); iter.hasNext();) {
    			Object element = iter.next();
    			if (element instanceof StringBuffer) {
    				writer.write(((StringBuffer) element).toString());
    			} else {
    				if (element instanceof String) {
    					String key = (String) element;
    					String value = (String) getProperty(key);
    					if (value != null) {
    						formatForOutput(key, s, true);
    						s.append('=');
    						formatForOutput(value, s, false);
    						writer.write(s.toString());
    					}
    				}
    			}
    		}
    		writer.flush();
    	}
     
    	private void addPropertKey(String key) {
    		contents.add(key);
    	}
     
    	private void addContent(String content) {
    		addContent(new StringBuffer(content));
    	}
     
    	private void addContent(StringBuffer content) {
    		contents.add(content);
    	}
     
    	/**
             * Formats a key or value for output in a properties file. See store for a
             * description of the format.
             * 
             * @param str
             *            the string to format
             * @param buffer
             *            the buffer to add it to
             * 
             * @param key
             *            true if all ' ' must be escaped for the key, false if only
             *            leading spaces must be escaped for the value
             * @see #store(OutputStream, String)
             */
    	private void formatForOutput(String str, StringBuffer buffer, boolean key) {
    		if (key) {
    			buffer.setLength(0);
    			buffer.ensureCapacity(str.length());
    		} else
    			buffer.ensureCapacity(buffer.length() + str.length());
    		boolean head = true;
    		int size = str.length();
    		for (int i = 0; i < size; i++) {
    			char c = str.charAt(i);
    			switch (c) {
    			case '\n':
    				buffer.append("\\n");
    				break;
    			case '\r':
    				buffer.append("\\r");
    				break;
    			case '\t':
    				buffer.append("\\t");
    				break;
    			case ' ':
    				buffer.append(head ? "\\ " : " ");
    				break;
    			case '\\':
    			case '!':
    			case '#':
    			case '=':
    			case ':':
    				buffer.append('\\').append(c);
    				break;
    			default:
    				if (c < ' ' || c > '~') {
    					String hex = Integer.toHexString(c);
    					buffer.append("\\u0000".substring(0, 6 - hex.length()));
    					buffer.append(hex);
    				} else
    					buffer.append(c);
    			}
    			if (c != ' ')
    				head = key;
    		}
    	}
     
    }
    Angelo

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 0
    Dernier message: 29/01/2012, 15h15
  2. Comment modifier une série de fichiers texte ?
    Par noufel dans le forum Scripts/Batch
    Réponses: 2
    Dernier message: 20/05/2010, 20h01
  3. Comment modifier une valeur dans un fichier à clef
    Par eudes dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 27/11/2009, 19h40
  4. Réponses: 0
    Dernier message: 15/10/2007, 12h18
  5. [TP]comment creer une disquette bootable (les fichiers)
    Par ludovic5532 dans le forum Turbo Pascal
    Réponses: 5
    Dernier message: 25/10/2003, 18h46

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo