KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > Properties


1 /*
2  * @(#)Properties.java 1.84 04/05/18
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util;
9
10 import java.io.IOException JavaDoc;
11 import java.io.PrintStream JavaDoc;
12 import java.io.PrintWriter JavaDoc;
13 import java.io.InputStream JavaDoc;
14 import java.io.OutputStream JavaDoc;
15 import java.io.OutputStreamWriter JavaDoc;
16 import java.io.BufferedWriter JavaDoc;
17
18 /**
19  * The <code>Properties</code> class represents a persistent set of
20  * properties. The <code>Properties</code> can be saved to a stream
21  * or loaded from a stream. Each key and its corresponding value in
22  * the property list is a string.
23  * <p>
24  * A property list can contain another property list as its
25  * "defaults"; this second property list is searched if
26  * the property key is not found in the original property list.
27  * <p>
28  * Because <code>Properties</code> inherits from <code>Hashtable</code>, the
29  * <code>put</code> and <code>putAll</code> methods can be applied to a
30  * <code>Properties</code> object. Their use is strongly discouraged as they
31  * allow the caller to insert entries whose keys or values are not
32  * <code>Strings</code>. The <code>setProperty</code> method should be used
33  * instead. If the <code>store</code> or <code>save</code> method is called
34  * on a "compromised" <code>Properties</code> object that contains a
35  * non-<code>String</code> key or value, the call will fail.
36  * <p>
37  * <a name="encoding"></a>
38  * <p> The {@link #load load} and {@link #store store} methods load and store
39  * properties in a simple line-oriented format specified below. This format
40  * uses the ISO 8859-1 character encoding. Characters that cannot be directly
41  * represented in this encoding can be written using
42  * <a HREF="http://java.sun.com/docs/books/jls/html/3.doc.html#100850">Unicode escapes</a>
43  * ; only a single 'u' character is allowed in an escape
44  * sequence. The native2ascii tool can be used to convert property files to and
45  * from other character encodings.
46  * <p>
47 * <p> The {@link #loadFromXML(InputStream)} and {@link
48  * #storeToXML(OutputStream, String, String)} methods load and store properties
49  * in a simple XML format. By default the UTF-8 character encoding is used,
50  * however a specific encoding may be specified if required. An XML properties
51  * document has the following DOCTYPE declaration:
52  *
53  * <pre>
54  * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
55  * </pre>
56  * Note that the system URI (http://java.sun.com/dtd/properties.dtd) is
57  * <i>not</i> accessed when exporting or importing properties; it merely
58  * serves as a string to uniquely identify the DTD, which is:
59  * <pre>
60  * &lt;?xml version="1.0" encoding="UTF-8"?&gt;
61  *
62  * &lt;!-- DTD for properties --&gt;
63  *
64  * &lt;!ELEMENT properties ( comment?, entry* ) &gt;
65  *
66  * &lt;!ATTLIST properties version CDATA #FIXED "1.0"&gt;
67  *
68  * &lt;!ELEMENT comment (#PCDATA) &gt;
69  *
70  * &lt;!ELEMENT entry (#PCDATA) &gt;
71  *
72  * &lt;!ATTLIST entry key CDATA #REQUIRED&gt;
73  * </pre>
74  *
75  * @see <a HREF="../../../tooldocs/solaris/native2ascii.html">native2ascii tool for Solaris</a>
76  * @see <a HREF="../../../tooldocs/windows/native2ascii.html">native2ascii tool for Windows</a>
77  *
78  * @author Arthur van Hoff
79  * @author Michael McCloskey
80  * @version 1.84, 05/18/04
81  * @since JDK1.0
82  */

83 public
84 class Properties extends Hashtable JavaDoc<Object JavaDoc,Object JavaDoc> {
85     /**
86      * use serialVersionUID from JDK 1.1.X for interoperability
87      */

88      private static final long serialVersionUID = 4112578634029874840L;
89
90     /**
91      * A property list that contains default values for any keys not
92      * found in this property list.
93      *
94      * @serial
95      */

96     protected Properties JavaDoc defaults;
97
98     /**
99      * Creates an empty property list with no default values.
100      */

101     public Properties() {
102     this(null);
103     }
104
105     /**
106      * Creates an empty property list with the specified defaults.
107      *
108      * @param defaults the defaults.
109      */

110     public Properties(Properties JavaDoc defaults) {
111     this.defaults = defaults;
112     }
113
114     /**
115      * Calls the <tt>Hashtable</tt> method <code>put</code>. Provided for
116      * parallelism with the <tt>getProperty</tt> method. Enforces use of
117      * strings for property keys and values. The value returned is the
118      * result of the <tt>Hashtable</tt> call to <code>put</code>.
119      *
120      * @param key the key to be placed into this property list.
121      * @param value the value corresponding to <tt>key</tt>.
122      * @return the previous value of the specified key in this property
123      * list, or <code>null</code> if it did not have one.
124      * @see #getProperty
125      * @since 1.2
126      */

127     public synchronized Object JavaDoc setProperty(String JavaDoc key, String JavaDoc value) {
128         return put(key, value);
129     }
130
131     /**
132      * Reads a property list (key and element pairs) from the input
133      * stream. The stream is assumed to be using the ISO 8859-1
134      * character encoding; that is each byte is one Latin1 character.
135      * Characters not in Latin1, and certain special characters, can
136      * be represented in keys and elements using escape sequences
137      * similar to those used for character and string literals (see <a
138      * HREF="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#100850">&sect;3.3</a>
139      * and <a
140      * HREF="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#101089">&sect;3.10.6</a>
141      * of the <i>Java Language Specification</i>).
142      *
143      * The differences from the character escape sequences used for
144      * characters and strings are:
145      *
146      * <ul>
147      * <li> Octal escapes are not recognized.
148      *
149      * <li> The character sequence <code>\b</code> does <i>not</i>
150      * represent a backspace character.
151      *
152      * <li> The method does not treat a backslash character,
153      * <code>\</code>, before a non-valid escape character as an
154      * error; the backslash is silently dropped. For example, in a
155      * Java string the sequence <code>"\z"</code> would cause a
156      * compile time error. In contrast, this method silently drops
157      * the backslash. Therefore, this method treats the two character
158      * sequence <code>"\b"</code> as equivalent to the single
159      * character <code>'b'</code>.
160      *
161      * <li> Escapes are not necessary for single and double quotes;
162      * however, by the rule above, single and double quote characters
163      * preceded by a backslash still yield single and double quote
164      * characters, respectively.
165      *
166      * </ul>
167      *
168      * An <code>IllegalArgumentException</code> is thrown if a
169      * malformed Unicode escape appears in the input.
170      *
171      * <p>
172      * This method processes input in terms of lines. A natural line
173      * of input is terminated either by a set of line terminator
174      * characters (<code>\n</code> or <code>\r</code> or
175      * <code>\r\n</code>) or by the end of the file. A natural line
176      * may be either a blank line, a comment line, or hold some part
177      * of a key-element pair. The logical line holding all the data
178      * for a key-element pair may be spread out across several adjacent
179      * natural lines by escaping the line terminator sequence with a
180      * backslash character, <code>\</code>. Note that a comment line
181      * cannot be extended in this manner; every natural line that is a
182      * comment must have its own comment indicator, as described
183      * below. If a logical line is continued over several natural
184      * lines, the continuation lines receive further processing, also
185      * described below. Lines are read from the input stream until
186      * end of file is reached.
187      *
188      * <p>
189      * A natural line that contains only white space characters is
190      * considered blank and is ignored. A comment line has an ASCII
191      * <code>'#'</code> or <code>'!'</code> as its first non-white
192      * space character; comment lines are also ignored and do not
193      * encode key-element information. In addition to line
194      * terminators, this method considers the characters space
195      * (<code>' '</code>, <code>'&#92;u0020'</code>), tab
196      * (<code>'\t'</code>, <code>'&#92;u0009'</code>), and form feed
197      * (<code>'\f'</code>, <code>'&#92;u000C'</code>) to be white
198      * space.
199      *
200      * <p>
201      * If a logical line is spread across several natural lines, the
202      * backslash escaping the line terminator sequence, the line
203      * terminator sequence, and any white space at the start the
204      * following line have no affect on the key or element values.
205      * The remainder of the discussion of key and element parsing will
206      * assume all the characters constituting the key and element
207      * appear on a single natural line after line continuation
208      * characters have been removed. Note that it is <i>not</i>
209      * sufficient to only examine the character preceding a line
210      * terminator sequence to see if the line terminator is
211      * escaped; there must be an odd number of contiguous backslashes
212      * for the line terminator to be escaped. Since the input is
213      * processed from left to right, a non-zero even number of
214      * 2<i>n</i> contiguous backslashes before a line terminator (or
215      * elsewhere) encodes <i>n</i> backslashes after escape
216      * processing.
217      *
218      * <p>
219      * The key contains all of the characters in the line starting
220      * with the first non-white space character and up to, but not
221      * including, the first unescaped <code>'='</code>,
222      * <code>':'</code>, or white space character other than a line
223      * terminator. All of these key termination characters may be
224      * included in the key by escaping them with a preceding backslash
225      * character; for example,<p>
226      *
227      * <code>\:\=</code><p>
228      *
229      * would be the two-character key <code>":="</code>. Line
230      * terminator characters can be included using <code>\r</code> and
231      * <code>\n</code> escape sequences. Any white space after the
232      * key is skipped; if the first non-white space character after
233      * the key is <code>'='</code> or <code>':'</code>, then it is
234      * ignored and any white space characters after it are also
235      * skipped. All remaining characters on the line become part of
236      * the associated element string; if there are no remaining
237      * characters, the element is the empty string
238      * <code>&quot;&quot;</code>. Once the raw character sequences
239      * constituting the key and element are identified, escape
240      * processing is performed as described above.
241      *
242      * <p>
243      * As an example, each of the following three lines specifies the key
244      * <code>"Truth"</code> and the associated element value
245      * <code>"Beauty"</code>:
246      * <p>
247      * <pre>
248      * Truth = Beauty
249      * Truth:Beauty
250      * Truth :Beauty
251      * </pre>
252      * As another example, the following three lines specify a single
253      * property:
254      * <p>
255      * <pre>
256      * fruits apple, banana, pear, \
257      * cantaloupe, watermelon, \
258      * kiwi, mango
259      * </pre>
260      * The key is <code>"fruits"</code> and the associated element is:
261      * <p>
262      * <pre>"apple, banana, pear, cantaloupe, watermelon, kiwi, mango"</pre>
263      * Note that a space appears before each <code>\</code> so that a space
264      * will appear after each comma in the final result; the <code>\</code>,
265      * line terminator, and leading white space on the continuation line are
266      * merely discarded and are <i>not</i> replaced by one or more other
267      * characters.
268      * <p>
269      * As a third example, the line:
270      * <p>
271      * <pre>cheeses
272      * </pre>
273      * specifies that the key is <code>"cheeses"</code> and the associated
274      * element is the empty string <code>""</code>.<p>
275      *
276      * @param inStream the input stream.
277      * @exception IOException if an error occurred when reading from the
278      * input stream.
279      * @throws IllegalArgumentException if the input stream contains a
280      * malformed Unicode escape sequence.
281      */

282     public synchronized void load(InputStream JavaDoc inStream) throws IOException JavaDoc {
283         char[] convtBuf = new char[1024];
284         LineReader lr = new LineReader(inStream);
285
286         int limit;
287         int keyLen;
288         int valueStart;
289         char c;
290         boolean hasSep;
291         boolean precedingBackslash;
292
293         while ((limit = lr.readLine()) >= 0) {
294             c = 0;
295             keyLen = 0;
296             valueStart = limit;
297             hasSep = false;
298
299         //System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
300
precedingBackslash = false;
301             while (keyLen < limit) {
302                 c = lr.lineBuf[keyLen];
303                 //need check if escaped.
304
if ((c == '=' || c == ':') && !precedingBackslash) {
305                     valueStart = keyLen + 1;
306                     hasSep = true;
307                     break;
308                 } else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash) {
309                     valueStart = keyLen + 1;
310                     break;
311                 }
312                 if (c == '\\') {
313                     precedingBackslash = !precedingBackslash;
314                 } else {
315                     precedingBackslash = false;
316                 }
317                 keyLen++;
318             }
319             while (valueStart < limit) {
320                 c = lr.lineBuf[valueStart];
321                 if (c != ' ' && c != '\t' && c != '\f') {
322                     if (!hasSep && (c == '=' || c == ':')) {
323                         hasSep = true;
324                     } else {
325                         break;
326                     }
327                 }
328                 valueStart++;
329             }
330             String JavaDoc key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
331             String JavaDoc value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
332         put(key, value);
333     }
334     }
335
336     /* read in a "logical line" from input stream, skip all comment and
337      * blank lines and filter out those leading whitespace characters
338      * ( , and ) from the beginning of a "natural line".
339      * Method returns the char length of the "logical line" and stores
340      * the line in "lineBuf".
341      */

342     class LineReader {
343         public LineReader(InputStream JavaDoc inStream) {
344             this.inStream = inStream;
345     }
346         byte[] inBuf = new byte[8192];
347         char[] lineBuf = new char[1024];
348         int inLimit = 0;
349         int inOff = 0;
350         InputStream JavaDoc inStream;
351
352         int readLine() throws IOException JavaDoc {
353             int len = 0;
354             char c = 0;
355
356             boolean skipWhiteSpace = true;
357             boolean isCommentLine = false;
358             boolean isNewLine = true;
359             boolean appendedLineBegin = false;
360             boolean precedingBackslash = false;
361         boolean skipLF = false;
362
363             while (true) {
364                 if (inOff >= inLimit) {
365                     inLimit = inStream.read(inBuf);
366             inOff = 0;
367             if (inLimit <= 0) {
368             if (len == 0 || isCommentLine) {
369                 return -1;
370             }
371             return len;
372             }
373         }
374                 //The line below is equivalent to calling a
375
//ISO8859-1 decoder.
376
c = (char) (0xff & inBuf[inOff++]);
377                 if (skipLF) {
378                     skipLF = false;
379             if (c == '\n') {
380                 continue;
381             }
382         }
383         if (skipWhiteSpace) {
384             if (c == ' ' || c == '\t' || c == '\f') {
385             continue;
386             }
387             if (!appendedLineBegin && (c == '\r' || c == '\n')) {
388             continue;
389             }
390             skipWhiteSpace = false;
391             appendedLineBegin = false;
392         }
393         if (isNewLine) {
394             isNewLine = false;
395             if (c == '#' || c == '!') {
396             isCommentLine = true;
397             continue;
398             }
399         }
400         
401         if (c != '\n' && c != '\r') {
402             lineBuf[len++] = c;
403             if (len == lineBuf.length) {
404                 int newLength = lineBuf.length * 2;
405                 if (newLength < 0) {
406                     newLength = Integer.MAX_VALUE;
407                 }
408             char[] buf = new char[newLength];
409             System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);
410             lineBuf = buf;
411             }
412             //flip the preceding backslash flag
413
if (c == '\\') {
414             precedingBackslash = !precedingBackslash;
415             } else {
416             precedingBackslash = false;
417             }
418         }
419         else {
420             // reached EOL
421
if (isCommentLine || len == 0) {
422             isCommentLine = false;
423             isNewLine = true;
424             skipWhiteSpace = true;
425             len = 0;
426             continue;
427             }
428             if (inOff >= inLimit) {
429             inLimit = inStream.read(inBuf);
430             inOff = 0;
431             if (inLimit <= 0) {
432                 return len;
433             }
434             }
435             if (precedingBackslash) {
436             len -= 1;
437             //skip the leading whitespace characters in following line
438
skipWhiteSpace = true;
439             appendedLineBegin = true;
440             precedingBackslash = false;
441             if (c == '\r') {
442                             skipLF = true;
443             }
444             } else {
445             return len;
446             }
447         }
448         }
449     }
450     }
451     
452     /*
453      * Converts encoded &#92;uxxxx to unicode chars
454      * and changes special saved chars to their original forms
455      */

456     private String JavaDoc loadConvert (char[] in, int off, int len, char[] convtBuf) {
457         if (convtBuf.length < len) {
458             int newLen = len * 2;
459             if (newLen < 0) {
460             newLen = Integer.MAX_VALUE;
461         }
462         convtBuf = new char[newLen];
463         }
464         char aChar;
465         char[] out = convtBuf;
466         int outLen = 0;
467         int end = off + len;
468
469         while (off < end) {
470             aChar = in[off++];
471             if (aChar == '\\') {
472                 aChar = in[off++];
473                 if(aChar == 'u') {
474                     // Read the xxxx
475
int value=0;
476             for (int i=0; i<4; i++) {
477                 aChar = in[off++];
478                 switch (aChar) {
479                   case '0': case '1': case '2': case '3': case '4':
480                   case '5': case '6': case '7': case '8': case '9':
481                      value = (value << 4) + aChar - '0';
482                  break;
483               case 'a': case 'b': case 'c':
484                           case 'd': case 'e': case 'f':
485                  value = (value << 4) + 10 + aChar - 'a';
486                  break;
487               case 'A': case 'B': case 'C':
488                           case 'D': case 'E': case 'F':
489                  value = (value << 4) + 10 + aChar - 'A';
490                  break;
491               default:
492                               throw new IllegalArgumentException JavaDoc(
493                                            "Malformed \\uxxxx encoding.");
494                         }
495                      }
496                     out[outLen++] = (char)value;
497                 } else {
498                     if (aChar == 't') aChar = '\t';
499                     else if (aChar == 'r') aChar = '\r';
500                     else if (aChar == 'n') aChar = '\n';
501                     else if (aChar == 'f') aChar = '\f';
502                     out[outLen++] = aChar;
503                 }
504             } else {
505             out[outLen++] = (char)aChar;
506             }
507         }
508         return new String JavaDoc (out, 0, outLen);
509     }
510
511     /*
512      * Converts unicodes to encoded &#92;uxxxx and escapes
513      * special characters with a preceding slash
514      */

515     private String JavaDoc saveConvert(String JavaDoc theString, boolean escapeSpace) {
516         int len = theString.length();
517         int bufLen = len * 2;
518         if (bufLen < 0) {
519             bufLen = Integer.MAX_VALUE;
520         }
521         StringBuffer JavaDoc outBuffer = new StringBuffer JavaDoc(bufLen);
522
523         for(int x=0; x<len; x++) {
524             char aChar = theString.charAt(x);
525             // Handle common case first, selecting largest block that
526
// avoids the specials below
527
if ((aChar > 61) && (aChar < 127)) {
528                 if (aChar == '\\') {
529                     outBuffer.append('\\'); outBuffer.append('\\');
530                     continue;
531                 }
532                 outBuffer.append(aChar);
533                 continue;
534             }
535             switch(aChar) {
536         case ' ':
537             if (x == 0 || escapeSpace)
538             outBuffer.append('\\');
539             outBuffer.append(' ');
540             break;
541                 case '\t':outBuffer.append('\\'); outBuffer.append('t');
542                           break;
543                 case '\n':outBuffer.append('\\'); outBuffer.append('n');
544                           break;
545                 case '\r':outBuffer.append('\\'); outBuffer.append('r');
546                           break;
547                 case '\f':outBuffer.append('\\'); outBuffer.append('f');
548                           break;
549                 case '=': // Fall through
550
case ':': // Fall through
551
case '#': // Fall through
552
case '!':
553                     outBuffer.append('\\'); outBuffer.append(aChar);
554                     break;
555                 default:
556                     if ((aChar < 0x0020) || (aChar > 0x007e)) {
557                         outBuffer.append('\\');
558                         outBuffer.append('u');
559                         outBuffer.append(toHex((aChar >> 12) & 0xF));
560                         outBuffer.append(toHex((aChar >> 8) & 0xF));
561                         outBuffer.append(toHex((aChar >> 4) & 0xF));
562                         outBuffer.append(toHex( aChar & 0xF));
563                     } else {
564                         outBuffer.append(aChar);
565                     }
566             }
567         }
568         return outBuffer.toString();
569     }
570
571     /**
572      * Calls the <code>store(OutputStream out, String comments)</code> method
573      * and suppresses IOExceptions that were thrown.
574      *
575      * @deprecated This method does not throw an IOException if an I/O error
576      * occurs while saving the property list. The preferred way to save a
577      * properties list is via the <code>store(OutputStream out,
578      * String comments)</code> method or the
579      * <code>storeToXML(OutputStream os, String comment)</code> method.
580      *
581      * @param out an output stream.
582      * @param comments a description of the property list.
583      * @exception ClassCastException if this <code>Properties</code> object
584      * contains any keys or values that are not
585      * <code>Strings</code>.
586      */

587     @Deprecated JavaDoc
588     public synchronized void save(OutputStream JavaDoc out, String JavaDoc comments) {
589         try {
590             store(out, comments);
591         } catch (IOException JavaDoc e) {
592         }
593     }
594
595     /**
596      * Writes this property list (key and element pairs) in this
597      * <code>Properties</code> table to the output stream in a format suitable
598      * for loading into a <code>Properties</code> table using the
599      * {@link #load(InputStream) load} method.
600      * The stream is written using the ISO 8859-1 character encoding.
601      * <p>
602      * Properties from the defaults table of this <code>Properties</code>
603      * table (if any) are <i>not</i> written out by this method.
604      * <p>
605      * If the comments argument is not null, then an ASCII <code>#</code>
606      * character, the comments string, and a line separator are first written
607      * to the output stream. Thus, the <code>comments</code> can serve as an
608      * identifying comment.
609      * <p>
610      * Next, a comment line is always written, consisting of an ASCII
611      * <code>#</code> character, the current date and time (as if produced
612      * by the <code>toString</code> method of <code>Date</code> for the
613      * current time), and a line separator as generated by the Writer.
614      * <p>
615      * Then every entry in this <code>Properties</code> table is
616      * written out, one per line. For each entry the key string is
617      * written, then an ASCII <code>=</code>, then the associated
618      * element string. Each character of the key and element strings
619      * is examined to see whether it should be rendered as an escape
620      * sequence. The ASCII characters <code>\</code>, tab, form feed,
621      * newline, and carriage return are written as <code>\\</code>,
622      * <code>\t</code>, <code>\f</code> <code>\n</code>, and
623      * <code>\r</code>, respectively. Characters less than
624      * <code>&#92;u0020</code> and characters greater than
625      * <code>&#92;u007E</code> are written as
626      * <code>&#92;u</code><i>xxxx</i> for the appropriate hexadecimal
627      * value <i>xxxx</i>. For the key, all space characters are
628      * written with a preceding <code>\</code> character. For the
629      * element, leading space characters, but not embedded or trailing
630      * space characters, are written with a preceding <code>\</code>
631      * character. The key and element characters <code>#</code>,
632      * <code>!</code>, <code>=</code>, and <code>:</code> are written
633      * with a preceding backslash to ensure that they are properly loaded.
634      * <p>
635      * After the entries have been written, the output stream is flushed. The
636      * output stream remains open after this method returns.
637      *
638      * @param out an output stream.
639      * @param comments a description of the property list.
640      * @exception IOException if writing this property list to the specified
641      * output stream throws an <tt>IOException</tt>.
642      * @exception ClassCastException if this <code>Properties</code> object
643      * contains any keys or values that are not <code>Strings</code>.
644      * @exception NullPointerException if <code>out</code> is null.
645      * @since 1.2
646      */

647     public synchronized void store(OutputStream JavaDoc out, String JavaDoc comments)
648     throws IOException JavaDoc
649     {
650         BufferedWriter JavaDoc awriter;
651         awriter = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(out, "8859_1"));
652         if (comments != null)
653             writeln(awriter, "#" + comments);
654         writeln(awriter, "#" + new Date JavaDoc().toString());
655         for (Enumeration JavaDoc e = keys(); e.hasMoreElements();) {
656             String JavaDoc key = (String JavaDoc)e.nextElement();
657             String JavaDoc val = (String JavaDoc)get(key);
658             key = saveConvert(key, true);
659
660         /* No need to escape embedded and trailing spaces for value, hence
661          * pass false to flag.
662          */

663             val = saveConvert(val, false);
664             writeln(awriter, key + "=" + val);
665         }
666         awriter.flush();
667     }
668
669     private static void writeln(BufferedWriter JavaDoc bw, String JavaDoc s) throws IOException JavaDoc {
670         bw.write(s);
671         bw.newLine();
672     }
673
674     /**
675      * Loads all of the properties represented by the XML document on the
676      * specified input stream into this properties table.
677      *
678      * <p>The XML document must have the following DOCTYPE declaration:
679      * <pre>
680      * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
681      * </pre>
682      * Furthermore, the document must satisfy the properties DTD described
683      * above.
684      *
685      * <p>The specified stream remains open after this method returns.
686      *
687      * @param in the input stream from which to read the XML document.
688      * @throws IOException if reading from the specified input stream
689      * results in an <tt>IOException</tt>.
690      * @throws InvalidPropertiesFormatException Data on input stream does not
691      * constitute a valid XML document with the mandated document type.
692      * @throws NullPointerException if <code>in</code> is null.
693      * @see #storeToXML(OutputStream, String, String)
694      * @since 1.5
695      */

696     public synchronized void loadFromXML(InputStream JavaDoc in)
697         throws IOException JavaDoc, InvalidPropertiesFormatException JavaDoc
698     {
699         if (in == null)
700             throw new NullPointerException JavaDoc();
701         XMLUtils.load(this, in);
702     }
703
704     /**
705      * Emits an XML document representing all of the properties contained
706      * in this table.
707      *
708      * <p> An invocation of this method of the form <tt>props.storeToXML(os,
709      * comment)</tt> behaves in exactly the same way as the invocation
710      * <tt>props.storeToXML(os, comment, "UTF-8");</tt>.
711      *
712      * @param os the output stream on which to emit the XML document.
713      * @param comment a description of the property list, or <code>null</code>
714      * if no comment is desired.
715      * @throws IOException if writing to the specified output stream
716      * results in an <tt>IOException</tt>.
717      * @throws NullPointerException if <code>os</code> is null.
718      * @see #loadFromXML(InputStream)
719      * @since 1.5
720      */

721     public synchronized void storeToXML(OutputStream JavaDoc os, String JavaDoc comment)
722         throws IOException JavaDoc
723     {
724         if (os == null)
725             throw new NullPointerException JavaDoc();
726         storeToXML(os, comment, "UTF-8");
727     }
728
729     /**
730      * Emits an XML document representing all of the properties contained
731      * in this table, using the specified encoding.
732      *
733      * <p>The XML document will have the following DOCTYPE declaration:
734      * <pre>
735      * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
736      * </pre>
737      *
738      *<p>If the specified comment is <code>null</code> then no comment
739      * will be stored in the document.
740      *
741      * <p>The specified stream remains open after this method returns.
742      *
743      * @param os the output stream on which to emit the XML document.
744      * @param comment a description of the property list, or <code>null</code>
745      * if no comment is desired.
746      * @throws IOException if writing to the specified output stream
747      * results in an <tt>IOException</tt>.
748      * @throws NullPointerException if <code>os</code> is <code>null</code>,
749      * or if <code>encoding</code> is <code>null</code>.
750      * @see #loadFromXML(InputStream)
751      * @since 1.5
752      */

753     public synchronized void storeToXML(OutputStream JavaDoc os, String JavaDoc comment,
754                                        String JavaDoc encoding)
755         throws IOException JavaDoc
756     {
757         if (os == null)
758             throw new NullPointerException JavaDoc();
759         XMLUtils.save(this, os, comment, encoding);
760     }
761
762     /**
763      * Searches for the property with the specified key in this property list.
764      * If the key is not found in this property list, the default property list,
765      * and its defaults, recursively, are then checked. The method returns
766      * <code>null</code> if the property is not found.
767      *
768      * @param key the property key.
769      * @return the value in this property list with the specified key value.
770      * @see #setProperty
771      * @see #defaults
772      */

773     public String JavaDoc getProperty(String JavaDoc key) {
774     Object JavaDoc oval = super.get(key);
775     String JavaDoc sval = (oval instanceof String JavaDoc) ? (String JavaDoc)oval : null;
776     return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
777     }
778
779     /**
780      * Searches for the property with the specified key in this property list.
781      * If the key is not found in this property list, the default property list,
782      * and its defaults, recursively, are then checked. The method returns the
783      * default value argument if the property is not found.
784      *
785      * @param key the hashtable key.
786      * @param defaultValue a default value.
787      *
788      * @return the value in this property list with the specified key value.
789      * @see #setProperty
790      * @see #defaults
791      */

792     public String JavaDoc getProperty(String JavaDoc key, String JavaDoc defaultValue) {
793     String JavaDoc val = getProperty(key);
794     return (val == null) ? defaultValue : val;
795     }
796
797     /**
798      * Returns an enumeration of all the keys in this property list,
799      * including distinct keys in the default property list if a key
800      * of the same name has not already been found from the main
801      * properties list.
802      *
803      * @return an enumeration of all the keys in this property list, including
804      * the keys in the default property list.
805      * @see java.util.Enumeration
806      * @see java.util.Properties#defaults
807      */

808     public Enumeration JavaDoc<?> propertyNames() {
809     Hashtable JavaDoc h = new Hashtable JavaDoc();
810     enumerate(h);
811     return h.keys();
812     }
813
814     /**
815      * Prints this property list out to the specified output stream.
816      * This method is useful for debugging.
817      *
818      * @param out an output stream.
819      */

820     public void list(PrintStream JavaDoc out) {
821     out.println("-- listing properties --");
822     Hashtable JavaDoc h = new Hashtable JavaDoc();
823     enumerate(h);
824     for (Enumeration JavaDoc e = h.keys() ; e.hasMoreElements() ;) {
825         String JavaDoc key = (String JavaDoc)e.nextElement();
826         String JavaDoc val = (String JavaDoc)h.get(key);
827         if (val.length() > 40) {
828                 val = val.substring(0, 37) + "...";
829         }
830         out.println(key + "=" + val);
831     }
832     }
833
834     /**
835      * Prints this property list out to the specified output stream.
836      * This method is useful for debugging.
837      *
838      * @param out an output stream.
839      * @since JDK1.1
840      */

841     /*
842      * Rather than use an anonymous inner class to share common code, this
843      * method is duplicated in order to ensure that a non-1.1 compiler can
844      * compile this file.
845      */

846     public void list(PrintWriter JavaDoc out) {
847     out.println("-- listing properties --");
848     Hashtable JavaDoc h = new Hashtable JavaDoc();
849     enumerate(h);
850     for (Enumeration JavaDoc e = h.keys() ; e.hasMoreElements() ;) {
851         String JavaDoc key = (String JavaDoc)e.nextElement();
852         String JavaDoc val = (String JavaDoc)h.get(key);
853         if (val.length() > 40) {
854         val = val.substring(0, 37) + "...";
855         }
856         out.println(key + "=" + val);
857     }
858     }
859
860     /**
861      * Enumerates all key/value pairs in the specified hashtable.
862      * @param h the hashtable
863      */

864     private synchronized void enumerate(Hashtable JavaDoc h) {
865     if (defaults != null) {
866         defaults.enumerate(h);
867     }
868     for (Enumeration JavaDoc e = keys() ; e.hasMoreElements() ;) {
869         String JavaDoc key = (String JavaDoc)e.nextElement();
870         h.put(key, get(key));
871     }
872     }
873
874     /**
875      * Convert a nibble to a hex character
876      * @param nibble the nibble to convert.
877      */

878     private static char toHex(int nibble) {
879     return hexDigit[(nibble & 0xF)];
880     }
881
882     /** A table of hex digits */
883     private static final char[] hexDigit = {
884     '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
885     };
886 }
887
Popular Tags