1 /* Properties.java -- a set of persistent properties
2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
41 import java.io.BufferedReader;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.InputStreamReader;
45 import java.io.OutputStream;
46 import java.io.OutputStreamWriter;
47 import java.io.PrintStream;
48 import java.io.PrintWriter;
51 * A set of persistent properties, which can be saved or loaded from a stream.
52 * A property list may also contain defaults, searched if the main list
53 * does not contain a property for a given key.
55 * An example of a properties file for the german language is given
56 * here. This extends the example given in ListResourceBundle.
57 * Create a file MyResource_de.properties with the following contents
58 * and put it in the CLASSPATH. (The character
59 * <code>\</code><code>u00e4</code> is the german umlaut)
64 s3=3. M\<code></code>u00e4rz 96
65 s4=Die Diskette ''{1}'' enth\<code></code>u00e4lt {0} in {2}.
71 s10={0,number} Dateien
72 s11=Das Formatieren schlug fehl mit folgender Exception: {0}
79 * <p>Although this is a sub class of a hash table, you should never
80 * insert anything other than strings to this property, or several
81 * methods, that need string keys and values, will fail. To ensure
82 * this, you should use the <code>get/setProperty</code> method instead
83 * of <code>get/put</code>.
85 * Properties are saved in ISO 8859-1 encoding, using Unicode escapes with
86 * a single <code>u</code> for any character which cannot be represented.
88 * @author Jochen Hoenicke
89 * @author Eric Blake (ebb9@email.byu.edu)
90 * @see PropertyResourceBundle
91 * @status updated to 1.4
93 public class Properties extends Hashtable
95 // WARNING: Properties is a CORE class in the bootstrap cycle. See the
96 // comments in vm/reference/java/lang/Runtime for implications of this fact.
99 * The property list that contains default values for any keys not
100 * in this property list.
102 * @serial the default properties
104 protected Properties defaults;
107 * Compatible with JDK 1.0+.
109 private static final long serialVersionUID = 4112578634029874840L;
112 * Creates a new empty property list with no default values.
119 * Create a new empty property list with the specified default values.
121 * @param defaults a Properties object containing the default values
123 public Properties(Properties defaults)
125 this.defaults = defaults;
129 * Adds the given key/value pair to this properties. This calls
130 * the hashtable method put.
132 * @param key the key for this property
133 * @param value the value for this property
134 * @return The old value for the given key
135 * @see #getProperty(String)
138 public Object setProperty(String key, String value)
140 return put(key, value);
144 * Reads a property list from an input stream. The stream should
145 * have the following format: <br>
147 * An empty line or a line starting with <code>#</code> or
148 * <code>!</code> is ignored. An backslash (<code>\</code>) at the
149 * end of the line makes the line continueing on the next line
150 * (but make sure there is no whitespace after the backslash).
151 * Otherwise, each line describes a key/value pair. <br>
153 * The chars up to the first whitespace, = or : are the key. You
154 * can include this caracters in the key, if you precede them with
155 * a backslash (<code>\</code>). The key is followed by optional
156 * whitespaces, optionally one <code>=</code> or <code>:</code>,
157 * and optionally some more whitespaces. The rest of the line is
158 * the resource belonging to the key. <br>
160 * Escape sequences <code>\t, \n, \r, \\, \", \', \!, \#, \ </code>(a
161 * space), and unicode characters with the
162 * <code>\\u</code><em>xxxx</em> notation are detected, and
163 * converted to the corresponding single character. <br>
166 <pre># This is a comment
168 k\:5 \ a string starting with space and ending with newline\n
169 # This is a multiline specification; note that the value contains
171 weekdays: Sunday,Monday,Tuesday,Wednesday,\\
172 Thursday,Friday,Saturday
173 # The safest way to include a space at the end of a value:
174 label = Name:\\u0020</pre>
176 * @param inStream the input stream
177 * @throws IOException if an error occurred when reading the input
178 * @throws NullPointerException if in is null
180 public void load(InputStream inStream) throws IOException
182 // The spec says that the file must be encoded using ISO-8859-1.
183 BufferedReader reader =
184 new BufferedReader(new InputStreamReader(inStream, "ISO-8859-1"));
187 while ((line = reader.readLine()) != null)
191 // Leading whitespaces must be deleted first.
192 while (pos < line.length()
193 && Character.isWhitespace(c = line.charAt(pos)))
196 // If empty line or begins with a comment character, skip this line.
197 if ((line.length() - pos) == 0
198 || line.charAt(pos) == '#' || line.charAt(pos) == '!')
201 // The characters up to the next Whitespace, ':', or '='
202 // describe the key. But look for escape sequences.
203 StringBuffer key = new StringBuffer();
204 while (pos < line.length()
205 && ! Character.isWhitespace(c = line.charAt(pos++))
206 && c != '=' && c != ':')
210 if (pos == line.length())
212 // The line continues on the next line. If there
213 // is no next line, just treat it as a key with an
215 line = reader.readLine();
219 while (pos < line.length()
220 && Character.isWhitespace(c = line.charAt(pos)))
225 c = line.charAt(pos++);
238 if (pos + 4 <= line.length())
240 char uni = (char) Integer.parseInt
241 (line.substring(pos, pos + 4), 16);
244 } // else throw exception?
256 boolean isDelim = (c == ':' || c == '=');
257 while (pos < line.length()
258 && Character.isWhitespace(c = line.charAt(pos)))
261 if (! isDelim && (c == ':' || c == '='))
264 while (pos < line.length()
265 && Character.isWhitespace(c = line.charAt(pos)))
269 StringBuffer element = new StringBuffer(line.length() - pos);
270 while (pos < line.length())
272 c = line.charAt(pos++);
275 if (pos == line.length())
277 // The line continues on the next line.
278 line = reader.readLine();
280 // We might have seen a backslash at the end of
281 // the file. The JDK ignores the backslash in
282 // this case, so we follow for compatibility.
287 while (pos < line.length()
288 && Character.isWhitespace(c = line.charAt(pos)))
290 element.ensureCapacity(line.length() - pos +
295 c = line.charAt(pos++);
299 element.append('\n');
302 element.append('\t');
305 element.append('\r');
308 if (pos + 4 <= line.length())
310 char uni = (char) Integer.parseInt
311 (line.substring(pos, pos + 4), 16);
314 } // else throw exception?
325 put(key.toString(), element.toString());
330 * Calls <code>store(OutputStream out, String header)</code> and
331 * ignores the IOException that may be thrown.
333 * @param out the stream to write to
334 * @param header a description of the property list
335 * @throws ClassCastException if this property contains any key or
336 * value that are not strings
337 * @deprecated use {@link #store(OutputStream, String)} instead
339 public void save(OutputStream out, String header)
345 catch (IOException ex)
351 * Writes the key/value pairs to the given output stream, in a format
352 * suitable for <code>load</code>.<br>
354 * If header is not null, this method writes a comment containing
355 * the header as first line to the stream. The next line (or first
356 * line if header is null) contains a comment with the current date.
357 * Afterwards the key/value pairs are written to the stream in the
358 * following format.<br>
360 * Each line has the form <code>key = value</code>. Newlines,
361 * Returns and tabs are written as <code>\n,\t,\r</code> resp.
362 * The characters <code>\, !, #, =</code> and <code>:</code> are
363 * preceeded by a backslash. Spaces are preceded with a backslash,
364 * if and only if they are at the beginning of the key. Characters
365 * that are not in the ascii range 33 to 127 are written in the
366 * <code>\</code><code>u</code>xxxx Form.<br>
368 * Following the listing, the output stream is flushed but left open.
370 * @param out the output stream
371 * @param header the header written in the first line, may be null
372 * @throws ClassCastException if this property contains any key or
373 * value that isn't a string
374 * @throws IOException if writing to the stream fails
375 * @throws NullPointerException if out is null
378 public void store(OutputStream out, String header) throws IOException
380 // The spec says that the file must be encoded using ISO-8859-1.
382 = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
384 writer.println("#" + header);
385 writer.println ("#" + Calendar.getInstance ().getTime ());
387 Iterator iter = entrySet ().iterator ();
389 StringBuffer s = new StringBuffer (); // Reuse the same buffer.
392 Map.Entry entry = (Map.Entry) iter.next ();
393 formatForOutput ((String) entry.getKey (), s, true);
395 formatForOutput ((String) entry.getValue (), s, false);
403 * Gets the property with the specified key in this property list.
404 * If the key is not found, the default property list is searched.
405 * If the property is not found in the default, null is returned.
407 * @param key The key for this property
408 * @return the value for the given key, or null if not found
409 * @throws ClassCastException if this property contains any key or
410 * value that isn't a string
412 * @see #setProperty(String, String)
413 * @see #getProperty(String, String)
415 public String getProperty(String key)
417 Properties prop = this;
418 // Eliminate tail recursion.
421 String value = (String) prop.get(key);
424 prop = prop.defaults;
426 while (prop != null);
431 * Gets the property with the specified key in this property list. If
432 * the key is not found, the default property list is searched. If the
433 * property is not found in the default, the specified defaultValue is
436 * @param key The key for this property
437 * @param defaultValue A default value
438 * @return The value for the given key
439 * @throws ClassCastException if this property contains any key or
440 * value that isn't a string
442 * @see #setProperty(String, String)
444 public String getProperty(String key, String defaultValue)
446 String prop = getProperty(key);
453 * Returns an enumeration of all keys in this property list, including
454 * the keys in the default property list.
456 * @return an Enumeration of all defined keys
458 public Enumeration propertyNames()
460 // We make a new Set that holds all the keys, then return an enumeration
461 // for that. This prevents modifications from ruining the enumeration,
462 // as well as ignoring duplicates.
463 Properties prop = this;
464 Set s = new HashSet();
465 // Eliminate tail recursion.
468 s.addAll(prop.keySet());
469 prop = prop.defaults;
471 while (prop != null);
472 return Collections.enumeration(s);
476 * Prints the key/value pairs to the given print stream. This is
477 * mainly useful for debugging purposes.
479 * @param out the print stream, where the key/value pairs are written to
480 * @throws ClassCastException if this property contains a key or a
481 * value that isn't a string
482 * @see #list(PrintWriter)
484 public void list(PrintStream out)
486 PrintWriter writer = new PrintWriter (out);
491 * Prints the key/value pairs to the given print writer. This is
492 * mainly useful for debugging purposes.
494 * @param out the print writer where the key/value pairs are written to
495 * @throws ClassCastException if this property contains a key or a
496 * value that isn't a string
497 * @see #list(PrintStream)
500 public void list(PrintWriter out)
502 out.println ("-- listing properties --");
504 Iterator iter = entrySet ().iterator ();
508 Map.Entry entry = (Map.Entry) iter.next ();
509 out.print ((String) entry.getKey () + "=");
511 // JDK 1.3/1.4 restrict the printed value, but not the key,
512 // to 40 characters, including the truncating ellipsis.
513 String s = (String ) entry.getValue ();
514 if (s != null && s.length () > 40)
515 out.println (s.substring (0, 37) + "...");
523 * Formats a key or value for output in a properties file.
524 * See store for a description of the format.
526 * @param str the string to format
527 * @param buffer the buffer to add it to
528 * @param key true if all ' ' must be escaped for the key, false if only
529 * leading spaces must be escaped for the value
530 * @see #store(OutputStream, String)
532 private void formatForOutput(String str, StringBuffer buffer, boolean key)
537 buffer.ensureCapacity(str.length());
540 buffer.ensureCapacity(buffer.length() + str.length());
542 int size = str.length();
543 for (int i = 0; i < size; i++)
545 char c = str.charAt(i);
549 buffer.append("\\n");
552 buffer.append("\\r");
555 buffer.append("\\t");
558 buffer.append(head ? "\\ " : " ");
565 buffer.append('\\').append(c);
568 if (c < ' ' || c > '~')
570 String hex = Integer.toHexString(c);
571 buffer.append("\\u0000".substring(0, 6 - hex.length()));
581 } // class Properties