Source Home >> Java Source 1.6.0 >> java.nio.charset.Charset V 0.09
  • 001/*
  • 002 * @(#)Charset.java 1.53 06/06/28
  • 003 *
  • 004 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
  • 005 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  • 006 */
  • 007
  • 008package java.nio.charset;
  • 009
  • 010import java.nio.ByteBuffer;
  • 011import java.nio.CharBuffer;
  • 012import java.nio.charset.spi.CharsetProvider;
  • 013import java.security.AccessController;
  • 014import java.security.AccessControlException;
  • 015import java.security.PrivilegedAction;
  • 016import java.util.Collections;
  • 017import java.util.HashSet;
  • 018import java.util.Iterator;
  • 019import java.util.Locale;
  • 020import java.util.Map;
  • 021import java.util.NoSuchElementException;
  • 022import java.util.Set;
  • 023import java.util.SortedMap;
  • 024import java.util.TreeMap;
  • 025import sun.misc.ASCIICaseInsensitiveComparator;
  • 026import sun.misc.Service;
  • 027import sun.misc.ServiceConfigurationError;
  • 028import sun.nio.cs.StandardCharsets;
  • 029import sun.nio.cs.ThreadLocalCoders;
  • 030import sun.security.action.GetPropertyAction;
  • 031
  • 032
  • 033/**
  • 034 * A named mapping between sequences of sixteen-bit Unicode <a
  • 035 * href="../../lang/Character.html#unicode">code units</a> and sequences of
  • 036 * bytes. This class defines methods for creating decoders and encoders and
  • 037 * for retrieving the various names associated with a charset. Instances of
  • 038 * this class are immutable.
  • 039 *
  • 040 * <p> This class also defines static methods for testing whether a particular
  • 041 * charset is supported, for locating charset instances by name, and for
  • 042 * constructing a map that contains every charset for which support is
  • 043 * available in the current Java virtual machine. Support for new charsets can
  • 044 * be added via the service-provider interface defined in the {@link
  • 045 * java.nio.charset.spi.CharsetProvider} class.
  • 046 *
  • 047 * <p> All of the methods defined in this class are safe for use by multiple
  • 048 * concurrent threads.
  • 049 *
  • 050 *
  • 051 * <a name="names"><a name="charenc">
  • 052 * <h4>Charset names</h4>
  • 053 *
  • 054 * <p> Charsets are named by strings composed of the following characters:
  • 055 *
  • 056 * <ul>
  • 057 *
  • 058 * <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt>
  • 059 * (<tt>'\u0041'</tt> through <tt>'\u005a'</tt>),
  • 060 *
  • 061 * <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
  • 062 * (<tt>'\u0061'</tt> through <tt>'\u007a'</tt>),
  • 063 *
  • 064 * <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
  • 065 * (<tt>'\u0030'</tt> through <tt>'\u0039'</tt>),
  • 066 *
  • 067 * <li> The dash character <tt>'-'</tt>
  • 068 * (<tt>'\u002d'</tt>, <small>HYPHEN-MINUS</small>),
  • 069 *
  • 070 * <li> The period character <tt>'.'</tt>
  • 071 * (<tt>'\u002e'</tt>, <small>FULL STOP</small>),
  • 072 *
  • 073 * <li> The colon character <tt>':'</tt>
  • 074 * (<tt>'\u003a'</tt>, <small>COLON</small>), and
  • 075 *
  • 076 * <li> The underscore character <tt>'_'</tt>
  • 077 * (<tt>'\u005f'</tt>, <small>LOW LINE</small>).
  • 078 *
  • 079 * </ul>
  • 080 *
  • 081 * A charset name must begin with either a letter or a digit. The empty string
  • 082 * is not a legal charset name. Charset names are not case-sensitive; that is,
  • 083 * case is always ignored when comparing charset names. Charset names
  • 084 * generally follow the conventions documented in <a
  • 085 * href="http://ietf.org/rfc/rfc2278.txt"><i>RFC 2278: IANA Charset
  • 086 * Registration Procedures</i></a>.
  • 087 *
  • 088 * <p> Every charset has a <i>canonical name</i> and may also have one or more
  • 089 * <i>aliases</i>. The canonical name is returned by the {@link #name() name} method
  • 090 * of this class. Canonical names are, by convention, usually in upper case.
  • 091 * The aliases of a charset are returned by the {@link #aliases() aliases}
  • 092 * method.
  • 093 *
  • 094 * <a name="hn">
  • 095 *
  • 096 * <p> Some charsets have an <i>historical name</i> that is defined for
  • 097 * compatibility with previous versions of the Java platform. A charset's
  • 098 * historical name is either its canonical name or one of its aliases. The
  • 099 * historical name is returned by the <tt>getEncoding()</tt> methods of the
  • 100 * {@link java.io.InputStreamReader#getEncoding InputStreamReader} and {@link
  • 101 * java.io.OutputStreamWriter#getEncoding OutputStreamWriter} classes.
  • 102 *
  • 103 * <a name="iana">
  • 104 *
  • 105 * <p> If a charset listed in the <a
  • 106 * href="http://www.iana.org/assignments/character-sets"><i>IANA Charset
  • 107 * Registry</i></a> is supported by an implementation of the Java platform then
  • 108 * its canonical name must be the name listed in the registry. Many charsets
  • 109 * are given more than one name in the registry, in which case the registry
  • 110 * identifies one of the names as <i>MIME-preferred</i>. If a charset has more
  • 111 * than one registry name then its canonical name must be the MIME-preferred
  • 112 * name and the other names in the registry must be valid aliases. If a
  • 113 * supported charset is not listed in the IANA registry then its canonical name
  • 114 * must begin with one of the strings <tt>"X-"</tt> or <tt>"x-"</tt>.
  • 115 *
  • 116 * <p> The IANA charset registry does change over time, and so the canonical
  • 117 * name and the aliases of a particular charset may also change over time. To
  • 118 * ensure compatibility it is recommended that no alias ever be removed from a
  • 119 * charset, and that if the canonical name of a charset is changed then its
  • 120 * previous canonical name be made into an alias.
  • 121 *
  • 122 *
  • 123 * <h4>Standard charsets</h4>
  • 124 *
  • 125 * <p> Every implementation of the Java platform is required to support the
  • 126 * following standard charsets. Consult the release documentation for your
  • 127 * implementation to see if any other charsets are supported. The behavior
  • 128 * of such optional charsets may differ between implementations.
  • 129 *
  • 130 * <blockquote><table width="80%" summary="Description of standard charsets">
  • 131 * <tr><th><p align="left">Charset</p></th><th><p align="left">Description</p></th></tr>
  • 132 * <tr><td valign=top><tt>US-ASCII</tt></td>
  • 133 * <td>Seven-bit ASCII, a.k.a. <tt>ISO646-US</tt>,
  • 134 * a.k.a. the Basic Latin block of the Unicode character set</td></tr>
  • 135 * <tr><td valign=top><tt>ISO-8859-1  </tt></td>
  • 136 * <td>ISO Latin Alphabet No. 1, a.k.a. <tt>ISO-LATIN-1</tt></td></tr>
  • 137 * <tr><td valign=top><tt>UTF-8</tt></td>
  • 138 * <td>Eight-bit UCS Transformation Format</td></tr>
  • 139 * <tr><td valign=top><tt>UTF-16BE</tt></td>
  • 140 * <td>Sixteen-bit UCS Transformation Format,
  • 141 * big-endian byte order</td></tr>
  • 142 * <tr><td valign=top><tt>UTF-16LE</tt></td>
  • 143 * <td>Sixteen-bit UCS Transformation Format,
  • 144 * little-endian byte order</td></tr>
  • 145 * <tr><td valign=top><tt>UTF-16</tt></td>
  • 146 * <td>Sixteen-bit UCS Transformation Format,
  • 147 * byte order identified by an optional byte-order mark</td></tr>
  • 148 * </table></blockquote>
  • 149 *
  • 150 * <p> The <tt>UTF-8</tt> charset is specified by <a
  • 151 * href="http://ietf.org/rfc/rfc2279.txt"><i>RFC 2279</i></a>; the
  • 152 * transformation format upon which it is based is specified in
  • 153 * Amendment 2 of ISO 10646-1 and is also described in the <a
  • 154 * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
  • 155 * Standard</i></a>.
  • 156 *
  • 157 * <p> The <tt>UTF-16</tt> charsets are specified by <a
  • 158 * href="http://ietf.org/rfc/rfc2781.txt"><i>RFC 2781</i></a>; the
  • 159 * transformation formats upon which they are based are specified in
  • 160 * Amendment 1 of ISO 10646-1 and are also described in the <a
  • 161 * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
  • 162 * Standard</i></a>.
  • 163 *
  • 164 * <p> The <tt>UTF-16</tt> charsets use sixteen-bit quantities and are
  • 165 * therefore sensitive to byte order. In these encodings the byte order of a
  • 166 * stream may be indicated by an initial <i>byte-order mark</i> represented by
  • 167 * the Unicode character <tt>'\uFEFF'</tt>. Byte-order marks are handled
  • 168 * as follows:
  • 169 *
  • 170 * <ul>
  • 171 *
  • 172 * <li><p> When decoding, the <tt>UTF-16BE</tt> and <tt>UTF-16LE</tt>
  • 173 * charsets ignore byte-order marks; when encoding, they do not write
  • 174 * byte-order marks. </p></li>
  • 175 *
  • 176 * <li><p> When decoding, the <tt>UTF-16</tt> charset interprets a byte-order
  • 177 * mark to indicate the byte order of the stream but defaults to big-endian
  • 178 * if there is no byte-order mark; when encoding, it uses big-endian byte
  • 179 * order and writes a big-endian byte-order mark. </p></li>
  • 180 *
  • 181 * </ul>
  • 182 *
  • 183 * In any case, when a byte-order mark is read at the beginning of a decoding
  • 184 * operation it is omitted from the resulting sequence of characters. Byte
  • 185 * order marks occuring after the first element of an input sequence are not
  • 186 * omitted since the same code is used to represent <small>ZERO-WIDTH
  • 187 * NON-BREAKING SPACE</small>.
  • 188 *
  • 189 * <p> Every instance of the Java virtual machine has a default charset, which
  • 190 * may or may not be one of the standard charsets. The default charset is
  • 191 * determined during virtual-machine startup and typically depends upon the
  • 192 * locale and charset being used by the underlying operating system. </p>
  • 193 *
  • 194 *
  • 195 * <h4>Terminology</h4>
  • 196 *
  • 197 * <p> The name of this class is taken from the terms used in <a
  • 198 * href="http://ietf.org/rfc/rfc2278.txt""><i>RFC 2278</i></a>. In that
  • 199 * document a <i>charset</i> is defined as the combination of a coded character
  • 200 * set and a character-encoding scheme.
  • 201 *
  • 202 * <p> A <i>coded character set</i> is a mapping between a set of abstract
  • 203 * characters and a set of integers. US-ASCII, ISO 8859-1,
  • 204 * JIS X 0201, and full Unicode, which is the same as
  • 205 * ISO 10646-1, are examples of coded character sets.
  • 206 *
  • 207 * <p> A <i>character-encoding scheme</i> is a mapping between a coded
  • 208 * character set and a set of octet (eight-bit byte) sequences. UTF-8, UCS-2,
  • 209 * UTF-16, ISO 2022, and EUC are examples of character-encoding schemes.
  • 210 * Encoding schemes are often associated with a particular coded character set;
  • 211 * UTF-8, for example, is used only to encode Unicode. Some schemes, however,
  • 212 * are associated with multiple character sets; EUC, for example, can be used
  • 213 * to encode characters in a variety of Asian character sets.
  • 214 *
  • 215 * <p> When a coded character set is used exclusively with a single
  • 216 * character-encoding scheme then the corresponding charset is usually named
  • 217 * for the character set; otherwise a charset is usually named for the encoding
  • 218 * scheme and, possibly, the locale of the character sets that it supports.
  • 219 * Hence <tt>US-ASCII</tt> is the name of the charset for US-ASCII while
  • 220 * <tt>EUC-JP</tt> is the name of the charset that encodes the
  • 221 * JIS X 0201, JIS X 0208, and JIS X 0212
  • 222 * character sets.
  • 223 *
  • 224 * <p> The native character encoding of the Java programming language is
  • 225 * UTF-16. A charset in the Java platform therefore defines a mapping between
  • 226 * sequences of sixteen-bit UTF-16 code units and sequences of bytes. </p>
  • 227 *
  • 228 *
  • 229 * @author Mark Reinhold
  • 230 * @author JSR-51 Expert Group
  • 231 * @version 1.53, 06/06/28
  • 232 * @since 1.4
  • 233 *
  • 234 * @see CharsetDecoder
  • 235 * @see CharsetEncoder
  • 236 * @see java.nio.charset.spi.CharsetProvider
  • 237 * @see java.lang.Character
  • 238 */
  • 239
  • 240public abstract class Charset
  • 241 implements Comparable<Charset>
  • 242{
  • 243
  • 244 /* -- Static methods -- */
  • 245
  • 246 private static String bugLevel = null;
  • 247
  • 248 static boolean atBugLevel(String bl) { // package-private
  • 249 if (bugLevel == null) {
  • 250 if (!sun.misc.VM.isBooted())
  • 251 return false;
  • 252 java.security.PrivilegedAction pa =
  • 253 new GetPropertyAction("sun.nio.cs.bugLevel");
  • 254 bugLevel = (String)AccessController.doPrivileged(pa);
  • 255 if (bugLevel == null)
  • 256 bugLevel = "";
  • 257 }
  • 258 return (bugLevel != null) && bugLevel.equals(bl);
  • 259 }
  • 260
  • 261 /**
  • 262 * Checks that the given string is a legal charset name. </p>
  • 263 *
  • 264 * @param s
  • 265 * A purported charset name
  • 266 *
  • 267 * @throws IllegalCharsetNameException
  • 268 * If the given name is not a legal charset name
  • 269 */
  • 270 private static void checkName(String s) {
  • 271 int n = s.length();
  • 272 if (!atBugLevel("1.4")) {
  • 273 if (n == 0)
  • 274 throw new IllegalCharsetNameException(s);
  • 275 }
  • 276 for (int i = 0; i < n; i++) {
  • 277 char c = s.charAt(i);
  • 278 if (c >= 'A' && c <= 'Z') continue;
  • 279 if (c >= 'a' && c <= 'z') continue;
  • 280 if (c >= '0' && c <= '9') continue;
  • 281 if (c == '-' && i != 0) continue;
  • 282 if (c == ':' && i != 0) continue;
  • 283 if (c == '_' && i != 0) continue;
  • 284 if (c == '.' && i != 0) continue;
  • 285 throw new IllegalCharsetNameException(s);
  • 286 }
  • 287 }
  • 288
  • 289 /* The standard set of charsets */
  • 290 private static CharsetProvider standardProvider = new StandardCharsets();
  • 291
  • 292 // Cache of the most-recently-returned charsets,
  • 293 // along with the names that were used to find them
  • 294 //
  • 295 private static volatile Object[] cache1 = null; // "Level 1" cache
  • 296 private static volatile Object[] cache2 = null; // "Level 2" cache
  • 297
  • 298 private static void cache(String charsetName, Charset cs) {
  • 299 cache2 = cache1;
  • 300 cache1 = new Object[] { charsetName, cs };
  • 301 }
  • 302
  • 303 // Creates an iterator that walks over the available providers, ignoring
  • 304 // those whose lookup or instantiation causes a security exception to be
  • 305 // thrown. Should be invoked with full privileges.
  • 306 //
  • 307 private static Iterator providers() {
  • 308 return new Iterator() {
  • 309
  • 310 Class c = java.nio.charset.spi.CharsetProvider.class;
  • 311 ClassLoader cl = ClassLoader.getSystemClassLoader();
  • 312 Iterator i = Service.providers(c, cl);
  • 313 Object next = null;
  • 314
  • 315 private boolean getNext() {
  • 316 while (next == null) {
  • 317 try {
  • 318 if (!i.hasNext())
  • 319 return false;
  • 320 next = i.next();
  • 321 } catch (ServiceConfigurationError sce) {
  • 322 if (sce.getCause() instanceof SecurityException) {
  • 323 // Ignore security exceptions
  • 324 continue;
  • 325 }
  • 326 throw sce;
  • 327 }
  • 328 }
  • 329 return true;
  • 330 }
  • 331
  • 332 public boolean hasNext() {
  • 333 return getNext();
  • 334 }
  • 335
  • 336 public Object next() {
  • 337 if (!getNext())
  • 338 throw new NoSuchElementException();
  • 339 Object n = next;
  • 340 next = null;
  • 341 return n;
  • 342 }
  • 343
  • 344 public void remove() {
  • 345 throw new UnsupportedOperationException();
  • 346 }
  • 347
  • 348 };
  • 349 }
  • 350
  • 351 // Thread-local gate to prevent recursive provider lookups
  • 352 private static ThreadLocal gate = new ThreadLocal();
  • 353
  • 354 private static Charset lookupViaProviders(final String charsetName) {
  • 355
  • 356 // The runtime startup sequence looks up standard charsets as a
  • 357 // consequence of the VM's invocation of System.initializeSystemClass
  • 358 // in order to, e.g., set system properties and encode filenames. At
  • 359 // that point the application class loader has not been initialized,
  • 360 // however, so we can't look for providers because doing so will cause
  • 361 // that loader to be prematurely initialized with incomplete
  • 362 // information.
  • 363 //
  • 364 if (!sun.misc.VM.isBooted())
  • 365 return null;
  • 366
  • 367 if (gate.get() != null)
  • 368 // Avoid recursive provider lookups
  • 369 return null;
  • 370 try {
  • 371 gate.set(gate);
  • 372
  • 373 return (Charset)AccessController
  • 374 .doPrivileged(new PrivilegedAction() {
  • 375 public Object run() {
  • 376 for (Iterator i = providers(); i.hasNext();) {
  • 377 CharsetProvider cp = (CharsetProvider)i.next();
  • 378 Charset cs = cp.charsetForName(charsetName);
  • 379 if (cs != null)
  • 380 return cs;
  • 381 }
  • 382 return null;
  • 383 }
  • 384 });
  • 385
  • 386 } finally {
  • 387 gate.set(null);
  • 388 }
  • 389 }
  • 390
  • 391 /* The extended set of charsets */
  • 392 private static Object extendedProviderLock = new Object();
  • 393 private static boolean extendedProviderProbed = false;
  • 394 private static CharsetProvider extendedProvider = null;
  • 395
  • 396 private static void probeExtendedProvider() {
  • 397 AccessController.doPrivileged(new PrivilegedAction() {
  • 398 public Object run() {
  • 399 try {
  • 400 Class epc
  • 401 = Class.forName("sun.nio.cs.ext.ExtendedCharsets");
  • 402 extendedProvider = (CharsetProvider)epc.newInstance();
  • 403 } catch (ClassNotFoundException x) {
  • 404 // Extended charsets not available
  • 405 // (charsets.jar not present)
  • 406 } catch (InstantiationException x) {
  • 407 throw new Error(x);
  • 408 } catch (IllegalAccessException x) {
  • 409 throw new Error(x);
  • 410 }
  • 411 return null;
  • 412 }
  • 413 });
  • 414 }
  • 415
  • 416 private static Charset lookupExtendedCharset(String charsetName) {
  • 417 CharsetProvider ecp = null;
  • 418 synchronized (extendedProviderLock) {
  • 419 if (!extendedProviderProbed) {
  • 420 probeExtendedProvider();
  • 421 extendedProviderProbed = true;
  • 422 }
  • 423 ecp = extendedProvider;
  • 424 }
  • 425 return (ecp != null) ? ecp.charsetForName(charsetName) : null;
  • 426 }
  • 427
  • 428 private static Charset lookup(String charsetName) {
  • 429 if (charsetName == null)
  • 430 throw new IllegalArgumentException("Null charset name");
  • 431
  • 432 Object[] a;
  • 433 if ((a = cache1) != null && charsetName.equals(a[0]))
  • 434 return (Charset)a[1];
  • 435 // We expect most programs to use one Charset repeatedly.
  • 436 // We convey a hint to this effect to the VM by putting the
  • 437 // level 1 cache miss code in a separate method.
  • 438 return lookup2(charsetName);
  • 439 }
  • 440
  • 441 private static Charset lookup2(String charsetName) {
  • 442 Object[] a;
  • 443 if ((a = cache2) != null && charsetName.equals(a[0])) {
  • 444 cache2 = cache1;
  • 445 cache1 = a;
  • 446 return (Charset)a[1];
  • 447 }
  • 448
  • 449 Charset cs;
  • 450 if ((cs = standardProvider.charsetForName(charsetName)) != null ||
  • 451 (cs = lookupExtendedCharset(charsetName)) != null ||
  • 452 (cs = lookupViaProviders(charsetName)) != null)
  • 453 {
  • 454 cache(charsetName, cs);
  • 455 return cs;
  • 456 }
  • 457
  • 458 /* Only need to check the name if we didn't find a charset for it */
  • 459 checkName(charsetName);
  • 460 return null;
  • 461 }
  • 462
  • 463 /**
  • 464 * Tells whether the named charset is supported. </p>
  • 465 *
  • 466 * @param charsetName
  • 467 * The name of the requested charset; may be either
  • 468 * a canonical name or an alias
  • 469 *
  • 470 * @return <tt>true</tt> if, and only if, support for the named charset
  • 471 * is available in the current Java virtual machine
  • 472 *
  • 473 * @throws IllegalCharsetNameException
  • 474 * If the given charset name is illegal
  • 475 *
  • 476 * @throws IllegalArgumentException
  • 477 * If the given <tt>charsetName</tt> is null
  • 478 */
  • 479 public static boolean isSupported(String charsetName) {
  • 480 return (lookup(charsetName) != null);
  • 481 }
  • 482
  • 483 /**
  • 484 * Returns a charset object for the named charset. </p>
  • 485 *
  • 486 * @param charsetName
  • 487 * The name of the requested charset; may be either
  • 488 * a canonical name or an alias
  • 489 *
  • 490 * @return A charset object for the named charset
  • 491 *
  • 492 * @throws IllegalCharsetNameException
  • 493 * If the given charset name is illegal
  • 494 *
  • 495 * @throws IllegalArgumentException
  • 496 * If the given <tt>charsetName</tt> is null
  • 497 *
  • 498 * @throws UnsupportedCharsetException
  • 499 * If no support for the named charset is available
  • 500 * in this instance of the Java virtual machine
  • 501 */
  • 502 public static Charset forName(String charsetName) {
  • 503 Charset cs = lookup(charsetName);
  • 504 if (cs != null)
  • 505 return cs;
  • 506 throw new UnsupportedCharsetException(charsetName);
  • 507 }
  • 508
  • 509 // Fold charsets from the given iterator into the given map, ignoring
  • 510 // charsets whose names already have entries in the map.
  • 511 //
  • 512 private static void put(Iterator i, Map m) {
  • 513 while (i.hasNext()) {
  • 514 Charset cs = (Charset)i.next();
  • 515 if (!m.containsKey(cs.name()))
  • 516 m.put(cs.name(), cs);
  • 517 }
  • 518 }
  • 519
  • 520 /**
  • 521 * Constructs a sorted map from canonical charset names to charset objects.
  • 522 *
  • 523 * <p> The map returned by this method will have one entry for each charset
  • 524 * for which support is available in the current Java virtual machine. If
  • 525 * two or more supported charsets have the same canonical name then the
  • 526 * resulting map will contain just one of them; which one it will contain
  • 527 * is not specified. </p>
  • 528 *
  • 529 * <p> The invocation of this method, and the subsequent use of the
  • 530 * resulting map, may cause time-consuming disk or network I/O operations
  • 531 * to occur. This method is provided for applications that need to
  • 532 * enumerate all of the available charsets, for example to allow user
  • 533 * charset selection. This method is not used by the {@link #forName
  • 534 * forName} method, which instead employs an efficient incremental lookup
  • 535 * algorithm.
  • 536 *
  • 537 * <p> This method may return different results at different times if new
  • 538 * charset providers are dynamically made available to the current Java
  • 539 * virtual machine. In the absence of such changes, the charsets returned
  • 540 * by this method are exactly those that can be retrieved via the {@link
  • 541 * #forName forName} method. </p>
  • 542 *
  • 543 * @return An immutable, case-insensitive map from canonical charset names
  • 544 * to charset objects
  • 545 */
  • 546 public static SortedMap<String,Charset> availableCharsets() {
  • 547 return (SortedMap)AccessController
  • 548 .doPrivileged(new PrivilegedAction() {
  • 549 public Object run() {
  • 550 TreeMap m = new TreeMap(ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER);
  • 551 put(standardProvider.charsets(), m);
  • 552 for (Iterator i = providers(); i.hasNext();) {
  • 553 CharsetProvider cp = (CharsetProvider)i.next();
  • 554 put(cp.charsets(), m);
  • 555 }
  • 556 return Collections.unmodifiableSortedMap(m);
  • 557 }
  • 558 });
  • 559 }
  • 560
  • 561 private static volatile Charset defaultCharset;
  • 562
  • 563 /**
  • 564 * Returns the default charset of this Java virtual machine.
  • 565 *
  • 566 * <p> The default charset is determined during virtual-machine startup and
  • 567 * typically depends upon the locale and charset of the underlying
  • 568 * operating system.
  • 569 *
  • 570 * @return A charset object for the default charset
  • 571 *
  • 572 * @since 1.5
  • 573 */
  • 574 public static Charset defaultCharset() {
  • 575 if (defaultCharset == null) {
  • 576 synchronized (Charset.class) {
  • 577 java.security.PrivilegedAction pa =
  • 578 new GetPropertyAction("file.encoding");
  • 579 String csn = (String)AccessController.doPrivileged(pa);
  • 580 Charset cs = lookup(csn);
  • 581 if (cs != null)
  • 582 defaultCharset = cs;
  • 583 else
  • 584 defaultCharset = forName("UTF-8");
  • 585 }
  • 586 }
  • 587 return defaultCharset;
  • 588 }
  • 589
  • 590
  • 591 /* -- Instance fields and methods -- */
  • 592
  • 593 private final String name; // tickles a bug in oldjavac
  • 594 private final String[] aliases; // tickles a bug in oldjavac
  • 595 private Set aliasSet = null;
  • 596
  • 597 /**
  • 598 * Initializes a new charset with the given canonical name and alias
  • 599 * set. </p>
  • 600 *
  • 601 * @param canonicalName
  • 602 * The canonical name of this charset
  • 603 *
  • 604 * @param aliases
  • 605 * An array of this charset's aliases, or null if it has no aliases
  • 606 *
  • 607 * @throws IllegalCharsetNameException
  • 608 * If the canonical name or any of the aliases are illegal
  • 609 */
  • 610 protected Charset(String canonicalName, String[] aliases) {
  • 611 checkName(canonicalName);
  • 612 String[] as = (aliases == null) ? new String[0] : aliases;
  • 613 for (int i = 0; i < as.length; i++)
  • 614 checkName(as[i]);
  • 615 this.name = canonicalName;
  • 616 this.aliases = as;
  • 617 }
  • 618
  • 619 /**
  • 620 * Returns this charset's canonical name. </p>
  • 621 *
  • 622 * @return The canonical name of this charset
  • 623 */
  • 624 public final String name() {
  • 625 return name;
  • 626 }
  • 627
  • 628 /**
  • 629 * Returns a set containing this charset's aliases. </p>
  • 630 *
  • 631 * @return An immutable set of this charset's aliases
  • 632 */
  • 633 public final Set<String> aliases() {
  • 634 if (aliasSet != null)
  • 635 return aliasSet;
  • 636 int n = aliases.length;
  • 637 HashSet hs = new HashSet(n);
  • 638 for (int i = 0; i < n; i++)
  • 639 hs.add(aliases[i]);
  • 640 aliasSet = Collections.unmodifiableSet(hs);
  • 641 return aliasSet;
  • 642 }
  • 643
  • 644 /**
  • 645 * Returns this charset's human-readable name for the default locale.
  • 646 *
  • 647 * <p> The default implementation of this method simply returns this
  • 648 * charset's canonical name. Concrete subclasses of this class may
  • 649 * override this method in order to provide a localized display name. </p>
  • 650 *
  • 651 * @return The display name of this charset in the default locale
  • 652 */
  • 653 public String displayName() {
  • 654 return name;
  • 655 }
  • 656
  • 657 /**
  • 658 * Tells whether or not this charset is registered in the <a
  • 659 * href="http://www.iana.org/assignments/character-sets">IANA Charset
  • 660 * Registry</a>. </p>
  • 661 *
  • 662 * @return <tt>true</tt> if, and only if, this charset is known by its
  • 663 * implementor to be registered with the IANA
  • 664 */
  • 665 public final boolean isRegistered() {
  • 666 return !name.startsWith("X-") && !name.startsWith("x-");
  • 667 }
  • 668
  • 669 /**
  • 670 * Returns this charset's human-readable name for the given locale.
  • 671 *
  • 672 * <p> The default implementation of this method simply returns this
  • 673 * charset's canonical name. Concrete subclasses of this class may
  • 674 * override this method in order to provide a localized display name. </p>
  • 675 *
  • 676 * @param locale
  • 677 * The locale for which the display name is to be retrieved
  • 678 *
  • 679 * @return The display name of this charset in the given locale
  • 680 */
  • 681 public String displayName(Locale locale) {
  • 682 return name;
  • 683 }
  • 684
  • 685 /**
  • 686 * Tells whether or not this charset contains the given charset.
  • 687 *
  • 688 * <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if,
  • 689 * and only if, every character representable in <i>D</i> is also
  • 690 * representable in <i>C</i>. If this relationship holds then it is
  • 691 * guaranteed that every string that can be encoded in <i>D</i> can also be
  • 692 * encoded in <i>C</i> without performing any replacements.
  • 693 *
  • 694 * <p> That <i>C</i> contains <i>D</i> does not imply that each character
  • 695 * representable in <i>C</i> by a particular byte sequence is represented
  • 696 * in <i>D</i> by the same byte sequence, although sometimes this is the
  • 697 * case.
  • 698 *
  • 699 * <p> Every charset contains itself.
  • 700 *
  • 701 * <p> This method computes an approximation of the containment relation:
  • 702 * If it returns <tt>true</tt> then the given charset is known to be
  • 703 * contained by this charset; if it returns <tt>false</tt>, however, then
  • 704 * it is not necessarily the case that the given charset is not contained
  • 705 * in this charset.
  • 706 *
  • 707 * @return <tt>true</tt> if the given charset is contained in this charset
  • 708 */
  • 709 public abstract boolean contains(Charset cs);
  • 710
  • 711 /**
  • 712 * Constructs a new decoder for this charset. </p>
  • 713 *
  • 714 * @return A new decoder for this charset
  • 715 */
  • 716 public abstract CharsetDecoder newDecoder();
  • 717
  • 718 /**
  • 719 * Constructs a new encoder for this charset. </p>
  • 720 *
  • 721 * @return A new encoder for this charset
  • 722 *
  • 723 * @throws UnsupportedOperationException
  • 724 * If this charset does not support encoding
  • 725 */
  • 726 public abstract CharsetEncoder newEncoder();
  • 727
  • 728 /**
  • 729 * Tells whether or not this charset supports encoding.
  • 730 *
  • 731 * <p> Nearly all charsets support encoding. The primary exceptions are
  • 732 * special-purpose <i>auto-detect</i> charsets whose decoders can determine
  • 733 * which of several possible encoding schemes is in use by examining the
  • 734 * input byte sequence. Such charsets do not support encoding because
  • 735 * there is no way to determine which encoding should be used on output.
  • 736 * Implementations of such charsets should override this method to return
  • 737 * <tt>false</tt>. </p>
  • 738 *
  • 739 * @return <tt>true</tt> if, and only if, this charset supports encoding
  • 740 */
  • 741 public boolean canEncode() {
  • 742 return true;
  • 743 }
  • 744
  • 745 /**
  • 746 * Convenience method that decodes bytes in this charset into Unicode
  • 747 * characters.
  • 748 *
  • 749 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
  • 750 * same result as the expression
  • 751 *
  • 752 * <pre>
  • 753 * cs.newDecoder()
  • 754 * .onMalformedInput(CodingErrorAction.REPLACE)
  • 755 * .onUnmappableCharacter(CodingErrorAction.REPLACE)
  • 756 * .decode(bb); </pre>
  • 757 *
  • 758 * except that it is potentially more efficient because it can cache
  • 759 * decoders between successive invocations.
  • 760 *
  • 761 * <p> This method always replaces malformed-input and unmappable-character
  • 762 * sequences with this charset's default replacement byte array. In order
  • 763 * to detect such sequences, use the {@link
  • 764 * CharsetDecoder#decode(java.nio.ByteBuffer)} method directly. </p>
  • 765 *
  • 766 * @param bb The byte buffer to be decoded
  • 767 *
  • 768 * @return A char buffer containing the decoded characters
  • 769 */
  • 770 public final CharBuffer decode(ByteBuffer bb) {
  • 771 try {
  • 772 return ThreadLocalCoders.decoderFor(this)
  • 773 .onMalformedInput(CodingErrorAction.REPLACE)
  • 774 .onUnmappableCharacter(CodingErrorAction.REPLACE)
  • 775 .decode(bb);
  • 776 } catch (CharacterCodingException x) {
  • 777 throw new Error(x); // Can't happen
  • 778 }
  • 779 }
  • 780
  • 781 /**
  • 782 * Convenience method that encodes Unicode characters into bytes in this
  • 783 * charset.
  • 784 *
  • 785 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
  • 786 * same result as the expression
  • 787 *
  • 788 * <pre>
  • 789 * cs.newEncoder()
  • 790 * .onMalformedInput(CodingErrorAction.REPLACE)
  • 791 * .onUnmappableCharacter(CodingErrorAction.REPLACE)
  • 792 * .encode(bb); </pre>
  • 793 *
  • 794 * except that it is potentially more efficient because it can cache
  • 795 * encoders between successive invocations.
  • 796 *
  • 797 * <p> This method always replaces malformed-input and unmappable-character
  • 798 * sequences with this charset's default replacement string. In order to
  • 799 * detect such sequences, use the {@link
  • 800 * CharsetEncoder#encode(java.nio.CharBuffer)} method directly. </p>
  • 801 *
  • 802 * @param cb The char buffer to be encoded
  • 803 *
  • 804 * @return A byte buffer containing the encoded characters
  • 805 */
  • 806 public final ByteBuffer encode(CharBuffer cb) {
  • 807 try {
  • 808 return ThreadLocalCoders.encoderFor(this)
  • 809 .onMalformedInput(CodingErrorAction.REPLACE)
  • 810 .onUnmappableCharacter(CodingErrorAction.REPLACE)
  • 811 .encode(cb);
  • 812 } catch (CharacterCodingException x) {
  • 813 throw new Error(x); // Can't happen
  • 814 }
  • 815 }
  • 816
  • 817 /**
  • 818 * Convenience method that encodes a string into bytes in this charset.
  • 819 *
  • 820 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
  • 821 * same result as the expression
  • 822 *
  • 823 * <pre>
  • 824 * cs.encode(CharBuffer.wrap(s)); </pre>
  • 825 *
  • 826 * @param str The string to be encoded
  • 827 *
  • 828 * @return A byte buffer containing the encoded characters
  • 829 */
  • 830 public final ByteBuffer encode(String str) {
  • 831 return encode(CharBuffer.wrap(str));
  • 832 }
  • 833
  • 834 /**
  • 835 * Compares this charset to another.
  • 836 *
  • 837 * <p> Charsets are ordered by their canonical names, without regard to
  • 838 * case. </p>
  • 839 *
  • 840 * @param that
  • 841 * The charset to which this charset is to be compared
  • 842 *
  • 843 * @return A negative integer, zero, or a positive integer as this charset
  • 844 * is less than, equal to, or greater than the specified charset
  • 845 */
  • 846 public final int compareTo(Charset that) {
  • 847 return (name().compareToIgnoreCase(that.name()));
  • 848 }
  • 849
  • 850 /**
  • 851 * Computes a hashcode for this charset. </p>
  • 852 *
  • 853 * @return An integer hashcode
  • 854 */
  • 855 public final int hashCode() {
  • 856 return name().hashCode();
  • 857 }
  • 858
  • 859 /**
  • 860 * Tells whether or not this object is equal to another.
  • 861 *
  • 862 * <p> Two charsets are equal if, and only if, they have the same canonical
  • 863 * names. A charset is never equal to any other type of object. </p>
  • 864 *
  • 865 * @return <tt>true</tt> if, and only if, this charset is equal to the
  • 866 * given object
  • 867 */
  • 868 public final boolean equals(Object ob) {
  • 869 if (!(ob instanceof Charset))
  • 870 return false;
  • 871 if (this == ob)
  • 872 return true;
  • 873 return name.equals(((Charset)ob).name());
  • 874 }
  • 875
  • 876 /**
  • 877 * Returns a string describing this charset. </p>
  • 878 *
  • 879 * @return A string describing this charset
  • 880 */
  • 881 public final String toString() {
  • 882 return name();
  • 883 }
  • 884
  • 885}

文件:Charset.java
包名:java.nio.charset
类名:Charset
继承:
接口:[Comparable]