2 * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
26 package java.nio.charset;
28 import java.nio.ByteBuffer;
29 import java.nio.CharBuffer;
30 import java.nio.charset.spi.CharsetProvider;
31 import java.security.AccessController;
32 import java.security.AccessControlException;
33 import java.security.PrivilegedAction;
34 import java.util.Collections;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.Locale;
39 import java.util.NoSuchElementException;
41 import java.util.ServiceLoader;
42 import java.util.ServiceConfigurationError;
43 import java.util.SortedMap;
44 import java.util.TreeMap;
45 import sun.misc.ASCIICaseInsensitiveComparator;
46 import sun.nio.cs.StandardCharsets;
47 import sun.nio.cs.ThreadLocalCoders;
48 import sun.security.action.GetPropertyAction;
52 * A named mapping between sequences of sixteen-bit Unicode <a
53 * href="../../lang/Character.html#unicode">code units</a> and sequences of
54 * bytes. This class defines methods for creating decoders and encoders and
55 * for retrieving the various names associated with a charset. Instances of
56 * this class are immutable.
58 * <p> This class also defines static methods for testing whether a particular
59 * charset is supported, for locating charset instances by name, and for
60 * constructing a map that contains every charset for which support is
61 * available in the current Java virtual machine. Support for new charsets can
62 * be added via the service-provider interface defined in the {@link
63 * java.nio.charset.spi.CharsetProvider} class.
65 * <p> All of the methods defined in this class are safe for use by multiple
69 * <a name="names"><a name="charenc">
70 * <h4>Charset names</h4>
72 * <p> Charsets are named by strings composed of the following characters:
76 * <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt>
77 * (<tt>'\u0041'</tt> through <tt>'\u005a'</tt>),
79 * <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
80 * (<tt>'\u0061'</tt> through <tt>'\u007a'</tt>),
82 * <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
83 * (<tt>'\u0030'</tt> through <tt>'\u0039'</tt>),
85 * <li> The dash character <tt>'-'</tt>
86 * (<tt>'\u002d'</tt>, <small>HYPHEN-MINUS</small>),
88 * <li> The plus character <tt>'+'</tt>
89 * (<tt>'\u002b'</tt>, <small>PLUS SIGN</small>),
91 * <li> The period character <tt>'.'</tt>
92 * (<tt>'\u002e'</tt>, <small>FULL STOP</small>),
94 * <li> The colon character <tt>':'</tt>
95 * (<tt>'\u003a'</tt>, <small>COLON</small>), and
97 * <li> The underscore character <tt>'_'</tt>
98 * (<tt>'\u005f'</tt>, <small>LOW LINE</small>).
102 * A charset name must begin with either a letter or a digit. The empty string
103 * is not a legal charset name. Charset names are not case-sensitive; that is,
104 * case is always ignored when comparing charset names. Charset names
105 * generally follow the conventions documented in <a
106 * href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC 2278: IANA Charset
107 * Registration Procedures</i></a>.
109 * <p> Every charset has a <i>canonical name</i> and may also have one or more
110 * <i>aliases</i>. The canonical name is returned by the {@link #name() name} method
111 * of this class. Canonical names are, by convention, usually in upper case.
112 * The aliases of a charset are returned by the {@link #aliases() aliases}
117 * <p> Some charsets have an <i>historical name</i> that is defined for
118 * compatibility with previous versions of the Java platform. A charset's
119 * historical name is either its canonical name or one of its aliases. The
120 * historical name is returned by the <tt>getEncoding()</tt> methods of the
121 * {@link java.io.InputStreamReader#getEncoding InputStreamReader} and {@link
122 * java.io.OutputStreamWriter#getEncoding OutputStreamWriter} classes.
126 * <p> If a charset listed in the <a
127 * href="http://www.iana.org/assignments/character-sets"><i>IANA Charset
128 * Registry</i></a> is supported by an implementation of the Java platform then
129 * its canonical name must be the name listed in the registry. Many charsets
130 * are given more than one name in the registry, in which case the registry
131 * identifies one of the names as <i>MIME-preferred</i>. If a charset has more
132 * than one registry name then its canonical name must be the MIME-preferred
133 * name and the other names in the registry must be valid aliases. If a
134 * supported charset is not listed in the IANA registry then its canonical name
135 * must begin with one of the strings <tt>"X-"</tt> or <tt>"x-"</tt>.
137 * <p> The IANA charset registry does change over time, and so the canonical
138 * name and the aliases of a particular charset may also change over time. To
139 * ensure compatibility it is recommended that no alias ever be removed from a
140 * charset, and that if the canonical name of a charset is changed then its
141 * previous canonical name be made into an alias.
144 * <h4>Standard charsets</h4>
146 * <a name="standard">
148 * <p> Every implementation of the Java platform is required to support the
149 * following standard charsets. Consult the release documentation for your
150 * implementation to see if any other charsets are supported. The behavior
151 * of such optional charsets may differ between implementations.
153 * <blockquote><table width="80%" summary="Description of standard charsets">
154 * <tr><th><p align="left">Charset</p></th><th><p align="left">Description</p></th></tr>
155 * <tr><td valign=top><tt>US-ASCII</tt></td>
156 * <td>Seven-bit ASCII, a.k.a. <tt>ISO646-US</tt>,
157 * a.k.a. the Basic Latin block of the Unicode character set</td></tr>
158 * <tr><td valign=top><tt>ISO-8859-1 </tt></td>
159 * <td>ISO Latin Alphabet No. 1, a.k.a. <tt>ISO-LATIN-1</tt></td></tr>
160 * <tr><td valign=top><tt>UTF-8</tt></td>
161 * <td>Eight-bit UCS Transformation Format</td></tr>
162 * <tr><td valign=top><tt>UTF-16BE</tt></td>
163 * <td>Sixteen-bit UCS Transformation Format,
164 * big-endian byte order</td></tr>
165 * <tr><td valign=top><tt>UTF-16LE</tt></td>
166 * <td>Sixteen-bit UCS Transformation Format,
167 * little-endian byte order</td></tr>
168 * <tr><td valign=top><tt>UTF-16</tt></td>
169 * <td>Sixteen-bit UCS Transformation Format,
170 * byte order identified by an optional byte-order mark</td></tr>
171 * </table></blockquote>
173 * <p> The <tt>UTF-8</tt> charset is specified by <a
174 * href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC 2279</i></a>; the
175 * transformation format upon which it is based is specified in
176 * Amendment 2 of ISO 10646-1 and is also described in the <a
177 * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
180 * <p> The <tt>UTF-16</tt> charsets are specified by <a
181 * href="http://www.ietf.org/rfc/rfc2781.txt"><i>RFC 2781</i></a>; the
182 * transformation formats upon which they are based are specified in
183 * Amendment 1 of ISO 10646-1 and are also described in the <a
184 * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
187 * <p> The <tt>UTF-16</tt> charsets use sixteen-bit quantities and are
188 * therefore sensitive to byte order. In these encodings the byte order of a
189 * stream may be indicated by an initial <i>byte-order mark</i> represented by
190 * the Unicode character <tt>'\uFEFF'</tt>. Byte-order marks are handled
195 * <li><p> When decoding, the <tt>UTF-16BE</tt> and <tt>UTF-16LE</tt>
196 * charsets interpret the initial byte-order marks as a <small>ZERO-WIDTH
197 * NON-BREAKING SPACE</small>; when encoding, they do not write
198 * byte-order marks. </p></li>
201 * <li><p> When decoding, the <tt>UTF-16</tt> charset interprets the
202 * byte-order mark at the beginning of the input stream to indicate the
203 * byte-order of the stream but defaults to big-endian if there is no
204 * byte-order mark; when encoding, it uses big-endian byte order and writes
205 * a big-endian byte-order mark. </p></li>
209 * In any case, byte order marks occuring after the first element of an
210 * input sequence are not omitted since the same code is used to represent
211 * <small>ZERO-WIDTH NON-BREAKING SPACE</small>.
213 * <p> Every instance of the Java virtual machine has a default charset, which
214 * may or may not be one of the standard charsets. The default charset is
215 * determined during virtual-machine startup and typically depends upon the
216 * locale and charset being used by the underlying operating system. </p>
218 * <p>The {@link StandardCharsets} class defines constants for each of the
221 * <h4>Terminology</h4>
223 * <p> The name of this class is taken from the terms used in
224 * <a href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC 2278</i></a>.
225 * In that document a <i>charset</i> is defined as the combination of
226 * one or more coded character sets and a character-encoding scheme.
227 * (This definition is confusing; some other software systems define
228 * <i>charset</i> as a synonym for <i>coded character set</i>.)
230 * <p> A <i>coded character set</i> is a mapping between a set of abstract
231 * characters and a set of integers. US-ASCII, ISO 8859-1,
232 * JIS X 0201, and Unicode are examples of coded character sets.
234 * <p> Some standards have defined a <i>character set</i> to be simply a
235 * set of abstract characters without an associated assigned numbering.
236 * An alphabet is an example of such a character set. However, the subtle
237 * distinction between <i>character set</i> and <i>coded character set</i>
238 * is rarely used in practice; the former has become a short form for the
239 * latter, including in the Java API specification.
241 * <p> A <i>character-encoding scheme</i> is a mapping between one or more
242 * coded character sets and a set of octet (eight-bit byte) sequences.
243 * UTF-8, UTF-16, ISO 2022, and EUC are examples of
244 * character-encoding schemes. Encoding schemes are often associated with
245 * a particular coded character set; UTF-8, for example, is used only to
246 * encode Unicode. Some schemes, however, are associated with multiple
247 * coded character sets; EUC, for example, can be used to encode
248 * characters in a variety of Asian coded character sets.
250 * <p> When a coded character set is used exclusively with a single
251 * character-encoding scheme then the corresponding charset is usually
252 * named for the coded character set; otherwise a charset is usually named
253 * for the encoding scheme and, possibly, the locale of the coded
254 * character sets that it supports. Hence <tt>US-ASCII</tt> is both the
255 * name of a coded character set and of the charset that encodes it, while
256 * <tt>EUC-JP</tt> is the name of the charset that encodes the
257 * JIS X 0201, JIS X 0208, and JIS X 0212
258 * coded character sets for the Japanese language.
260 * <p> The native character encoding of the Java programming language is
261 * UTF-16. A charset in the Java platform therefore defines a mapping
262 * between sequences of sixteen-bit UTF-16 code units (that is, sequences
263 * of chars) and sequences of bytes. </p>
266 * @author Mark Reinhold
267 * @author JSR-51 Expert Group
270 * @see CharsetDecoder
271 * @see CharsetEncoder
272 * @see java.nio.charset.spi.CharsetProvider
273 * @see java.lang.Character
276 public abstract class Charset
277 implements Comparable<Charset>
280 /* -- Static methods -- */
282 private static volatile String bugLevel = null;
284 static boolean atBugLevel(String bl) { // package-private
285 String level = bugLevel;
287 if (!sun.misc.VM.isBooted())
289 bugLevel = level = AccessController.doPrivileged(
290 new GetPropertyAction("sun.nio.cs.bugLevel", ""));
292 return level.equals(bl);
296 * Checks that the given string is a legal charset name. </p>
299 * A purported charset name
301 * @throws IllegalCharsetNameException
302 * If the given name is not a legal charset name
304 private static void checkName(String s) {
306 if (!atBugLevel("1.4")) {
308 throw new IllegalCharsetNameException(s);
310 for (int i = 0; i < n; i++) {
311 char c = s.charAt(i);
312 if (c >= 'A' && c <= 'Z') continue;
313 if (c >= 'a' && c <= 'z') continue;
314 if (c >= '0' && c <= '9') continue;
315 if (c == '-' && i != 0) continue;
316 if (c == '+' && i != 0) continue;
317 if (c == ':' && i != 0) continue;
318 if (c == '_' && i != 0) continue;
319 if (c == '.' && i != 0) continue;
320 throw new IllegalCharsetNameException(s);
324 /* The standard set of charsets */
325 private static CharsetProvider standardProvider = new StandardCharsets();
327 // Cache of the most-recently-returned charsets,
328 // along with the names that were used to find them
330 private static volatile Object[] cache1 = null; // "Level 1" cache
331 private static volatile Object[] cache2 = null; // "Level 2" cache
333 private static void cache(String charsetName, Charset cs) {
335 cache1 = new Object[] { charsetName, cs };
338 // Creates an iterator that walks over the available providers, ignoring
339 // those whose lookup or instantiation causes a security exception to be
340 // thrown. Should be invoked with full privileges.
342 private static Iterator providers() {
343 return new Iterator() {
345 ClassLoader cl = ClassLoader.getSystemClassLoader();
346 ServiceLoader<CharsetProvider> sl =
347 ServiceLoader.load(CharsetProvider.class, cl);
348 Iterator<CharsetProvider> i = sl.iterator();
352 private boolean getNext() {
353 while (next == null) {
358 } catch (ServiceConfigurationError sce) {
359 if (sce.getCause() instanceof SecurityException) {
360 // Ignore security exceptions
369 public boolean hasNext() {
373 public Object next() {
375 throw new NoSuchElementException();
381 public void remove() {
382 throw new UnsupportedOperationException();
388 // Thread-local gate to prevent recursive provider lookups
389 private static ThreadLocal<ThreadLocal> gate = new ThreadLocal<ThreadLocal>();
391 private static Charset lookupViaProviders(final String charsetName) {
393 // The runtime startup sequence looks up standard charsets as a
394 // consequence of the VM's invocation of System.initializeSystemClass
395 // in order to, e.g., set system properties and encode filenames. At
396 // that point the application class loader has not been initialized,
397 // however, so we can't look for providers because doing so will cause
398 // that loader to be prematurely initialized with incomplete
401 if (!sun.misc.VM.isBooted())
404 if (gate.get() != null)
405 // Avoid recursive provider lookups
410 return AccessController.doPrivileged(
411 new PrivilegedAction<Charset>() {
412 public Charset run() {
413 for (Iterator i = providers(); i.hasNext();) {
414 CharsetProvider cp = (CharsetProvider)i.next();
415 Charset cs = cp.charsetForName(charsetName);
428 /* The extended set of charsets */
429 private static Object extendedProviderLock = new Object();
430 private static boolean extendedProviderProbed = false;
431 private static CharsetProvider extendedProvider = null;
433 private static void probeExtendedProvider() {
434 AccessController.doPrivileged(new PrivilegedAction<Object>() {
435 public Object run() {
438 = Class.forName("sun.nio.cs.ext.ExtendedCharsets");
439 extendedProvider = (CharsetProvider)epc.newInstance();
440 } catch (ClassNotFoundException x) {
441 // Extended charsets not available
442 // (charsets.jar not present)
443 } catch (InstantiationException x) {
445 } catch (IllegalAccessException x) {
453 private static Charset lookupExtendedCharset(String charsetName) {
454 CharsetProvider ecp = null;
455 synchronized (extendedProviderLock) {
456 if (!extendedProviderProbed) {
457 probeExtendedProvider();
458 extendedProviderProbed = true;
460 ecp = extendedProvider;
462 return (ecp != null) ? ecp.charsetForName(charsetName) : null;
465 private static Charset lookup(String charsetName) {
466 if (charsetName == null)
467 throw new IllegalArgumentException("Null charset name");
470 if ((a = cache1) != null && charsetName.equals(a[0]))
471 return (Charset)a[1];
472 // We expect most programs to use one Charset repeatedly.
473 // We convey a hint to this effect to the VM by putting the
474 // level 1 cache miss code in a separate method.
475 return lookup2(charsetName);
478 private static Charset lookup2(String charsetName) {
480 if ((a = cache2) != null && charsetName.equals(a[0])) {
483 return (Charset)a[1];
487 if ((cs = standardProvider.charsetForName(charsetName)) != null ||
488 (cs = lookupExtendedCharset(charsetName)) != null ||
489 (cs = lookupViaProviders(charsetName)) != null)
491 cache(charsetName, cs);
495 /* Only need to check the name if we didn't find a charset for it */
496 checkName(charsetName);
501 * Tells whether the named charset is supported. </p>
504 * The name of the requested charset; may be either
505 * a canonical name or an alias
507 * @return <tt>true</tt> if, and only if, support for the named charset
508 * is available in the current Java virtual machine
510 * @throws IllegalCharsetNameException
511 * If the given charset name is illegal
513 * @throws IllegalArgumentException
514 * If the given <tt>charsetName</tt> is null
516 public static boolean isSupported(String charsetName) {
517 return (lookup(charsetName) != null);
521 * Returns a charset object for the named charset. </p>
524 * The name of the requested charset; may be either
525 * a canonical name or an alias
527 * @return A charset object for the named charset
529 * @throws IllegalCharsetNameException
530 * If the given charset name is illegal
532 * @throws IllegalArgumentException
533 * If the given <tt>charsetName</tt> is null
535 * @throws UnsupportedCharsetException
536 * If no support for the named charset is available
537 * in this instance of the Java virtual machine
539 public static Charset forName(String charsetName) {
540 Charset cs = lookup(charsetName);
543 throw new UnsupportedCharsetException(charsetName);
546 // Fold charsets from the given iterator into the given map, ignoring
547 // charsets whose names already have entries in the map.
549 private static void put(Iterator<Charset> i, Map<String,Charset> m) {
550 while (i.hasNext()) {
551 Charset cs = i.next();
552 if (!m.containsKey(cs.name()))
553 m.put(cs.name(), cs);
558 * Constructs a sorted map from canonical charset names to charset objects.
560 * <p> The map returned by this method will have one entry for each charset
561 * for which support is available in the current Java virtual machine. If
562 * two or more supported charsets have the same canonical name then the
563 * resulting map will contain just one of them; which one it will contain
564 * is not specified. </p>
566 * <p> The invocation of this method, and the subsequent use of the
567 * resulting map, may cause time-consuming disk or network I/O operations
568 * to occur. This method is provided for applications that need to
569 * enumerate all of the available charsets, for example to allow user
570 * charset selection. This method is not used by the {@link #forName
571 * forName} method, which instead employs an efficient incremental lookup
574 * <p> This method may return different results at different times if new
575 * charset providers are dynamically made available to the current Java
576 * virtual machine. In the absence of such changes, the charsets returned
577 * by this method are exactly those that can be retrieved via the {@link
578 * #forName forName} method. </p>
580 * @return An immutable, case-insensitive map from canonical charset names
583 public static SortedMap<String,Charset> availableCharsets() {
584 return AccessController.doPrivileged(
585 new PrivilegedAction<SortedMap<String,Charset>>() {
586 public SortedMap<String,Charset> run() {
587 TreeMap<String,Charset> m =
588 new TreeMap<String,Charset>(
589 ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER);
590 put(standardProvider.charsets(), m);
591 for (Iterator i = providers(); i.hasNext();) {
592 CharsetProvider cp = (CharsetProvider)i.next();
593 put(cp.charsets(), m);
595 return Collections.unmodifiableSortedMap(m);
600 private static volatile Charset defaultCharset;
603 * Returns the default charset of this Java virtual machine.
605 * <p> The default charset is determined during virtual-machine startup and
606 * typically depends upon the locale and charset of the underlying
609 * @return A charset object for the default charset
613 public static Charset defaultCharset() {
614 if (defaultCharset == null) {
615 synchronized (Charset.class) {
616 String csn = AccessController.doPrivileged(
617 new GetPropertyAction("file.encoding"));
618 Charset cs = lookup(csn);
622 defaultCharset = forName("UTF-8");
625 return defaultCharset;
629 /* -- Instance fields and methods -- */
631 private final String name; // tickles a bug in oldjavac
632 private final String[] aliases; // tickles a bug in oldjavac
633 private Set<String> aliasSet = null;
636 * Initializes a new charset with the given canonical name and alias
639 * @param canonicalName
640 * The canonical name of this charset
643 * An array of this charset's aliases, or null if it has no aliases
645 * @throws IllegalCharsetNameException
646 * If the canonical name or any of the aliases are illegal
648 protected Charset(String canonicalName, String[] aliases) {
649 checkName(canonicalName);
650 String[] as = (aliases == null) ? new String[0] : aliases;
651 for (int i = 0; i < as.length; i++)
653 this.name = canonicalName;
658 * Returns this charset's canonical name. </p>
660 * @return The canonical name of this charset
662 public final String name() {
667 * Returns a set containing this charset's aliases. </p>
669 * @return An immutable set of this charset's aliases
671 public final Set<String> aliases() {
672 if (aliasSet != null)
674 int n = aliases.length;
675 HashSet<String> hs = new HashSet<String>(n);
676 for (int i = 0; i < n; i++)
678 aliasSet = Collections.unmodifiableSet(hs);
683 * Returns this charset's human-readable name for the default locale.
685 * <p> The default implementation of this method simply returns this
686 * charset's canonical name. Concrete subclasses of this class may
687 * override this method in order to provide a localized display name. </p>
689 * @return The display name of this charset in the default locale
691 public String displayName() {
696 * Tells whether or not this charset is registered in the <a
697 * href="http://www.iana.org/assignments/character-sets">IANA Charset
700 * @return <tt>true</tt> if, and only if, this charset is known by its
701 * implementor to be registered with the IANA
703 public final boolean isRegistered() {
704 return !name.startsWith("X-") && !name.startsWith("x-");
708 * Returns this charset's human-readable name for the given locale.
710 * <p> The default implementation of this method simply returns this
711 * charset's canonical name. Concrete subclasses of this class may
712 * override this method in order to provide a localized display name. </p>
715 * The locale for which the display name is to be retrieved
717 * @return The display name of this charset in the given locale
719 public String displayName(Locale locale) {
724 * Tells whether or not this charset contains the given charset.
726 * <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if,
727 * and only if, every character representable in <i>D</i> is also
728 * representable in <i>C</i>. If this relationship holds then it is
729 * guaranteed that every string that can be encoded in <i>D</i> can also be
730 * encoded in <i>C</i> without performing any replacements.
732 * <p> That <i>C</i> contains <i>D</i> does not imply that each character
733 * representable in <i>C</i> by a particular byte sequence is represented
734 * in <i>D</i> by the same byte sequence, although sometimes this is the
737 * <p> Every charset contains itself.
739 * <p> This method computes an approximation of the containment relation:
740 * If it returns <tt>true</tt> then the given charset is known to be
741 * contained by this charset; if it returns <tt>false</tt>, however, then
742 * it is not necessarily the case that the given charset is not contained
745 * @return <tt>true</tt> if the given charset is contained in this charset
747 public abstract boolean contains(Charset cs);
750 * Constructs a new decoder for this charset. </p>
752 * @return A new decoder for this charset
754 public abstract CharsetDecoder newDecoder();
757 * Constructs a new encoder for this charset. </p>
759 * @return A new encoder for this charset
761 * @throws UnsupportedOperationException
762 * If this charset does not support encoding
764 public abstract CharsetEncoder newEncoder();
767 * Tells whether or not this charset supports encoding.
769 * <p> Nearly all charsets support encoding. The primary exceptions are
770 * special-purpose <i>auto-detect</i> charsets whose decoders can determine
771 * which of several possible encoding schemes is in use by examining the
772 * input byte sequence. Such charsets do not support encoding because
773 * there is no way to determine which encoding should be used on output.
774 * Implementations of such charsets should override this method to return
775 * <tt>false</tt>. </p>
777 * @return <tt>true</tt> if, and only if, this charset supports encoding
779 public boolean canEncode() {
784 * Convenience method that decodes bytes in this charset into Unicode
787 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
788 * same result as the expression
792 * .onMalformedInput(CodingErrorAction.REPLACE)
793 * .onUnmappableCharacter(CodingErrorAction.REPLACE)
794 * .decode(bb); </pre>
796 * except that it is potentially more efficient because it can cache
797 * decoders between successive invocations.
799 * <p> This method always replaces malformed-input and unmappable-character
800 * sequences with this charset's default replacement byte array. In order
801 * to detect such sequences, use the {@link
802 * CharsetDecoder#decode(java.nio.ByteBuffer)} method directly. </p>
804 * @param bb The byte buffer to be decoded
806 * @return A char buffer containing the decoded characters
808 public final CharBuffer decode(ByteBuffer bb) {
810 return ThreadLocalCoders.decoderFor(this)
811 .onMalformedInput(CodingErrorAction.REPLACE)
812 .onUnmappableCharacter(CodingErrorAction.REPLACE)
814 } catch (CharacterCodingException x) {
815 throw new Error(x); // Can't happen
820 * Convenience method that encodes Unicode characters into bytes in this
823 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
824 * same result as the expression
828 * .onMalformedInput(CodingErrorAction.REPLACE)
829 * .onUnmappableCharacter(CodingErrorAction.REPLACE)
830 * .encode(bb); </pre>
832 * except that it is potentially more efficient because it can cache
833 * encoders between successive invocations.
835 * <p> This method always replaces malformed-input and unmappable-character
836 * sequences with this charset's default replacement string. In order to
837 * detect such sequences, use the {@link
838 * CharsetEncoder#encode(java.nio.CharBuffer)} method directly. </p>
840 * @param cb The char buffer to be encoded
842 * @return A byte buffer containing the encoded characters
844 public final ByteBuffer encode(CharBuffer cb) {
846 return ThreadLocalCoders.encoderFor(this)
847 .onMalformedInput(CodingErrorAction.REPLACE)
848 .onUnmappableCharacter(CodingErrorAction.REPLACE)
850 } catch (CharacterCodingException x) {
851 throw new Error(x); // Can't happen
856 * Convenience method that encodes a string into bytes in this charset.
858 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
859 * same result as the expression
862 * cs.encode(CharBuffer.wrap(s)); </pre>
864 * @param str The string to be encoded
866 * @return A byte buffer containing the encoded characters
868 public final ByteBuffer encode(String str) {
869 return encode(CharBuffer.wrap(str));
873 * Compares this charset to another.
875 * <p> Charsets are ordered by their canonical names, without regard to
879 * The charset to which this charset is to be compared
881 * @return A negative integer, zero, or a positive integer as this charset
882 * is less than, equal to, or greater than the specified charset
884 public final int compareTo(Charset that) {
885 return (name().compareToIgnoreCase(that.name()));
889 * Computes a hashcode for this charset. </p>
891 * @return An integer hashcode
893 public final int hashCode() {
894 return name().hashCode();
898 * Tells whether or not this object is equal to another.
900 * <p> Two charsets are equal if, and only if, they have the same canonical
901 * names. A charset is never equal to any other type of object. </p>
903 * @return <tt>true</tt> if, and only if, this charset is equal to the
906 public final boolean equals(Object ob) {
907 if (!(ob instanceof Charset))
911 return name.equals(((Charset)ob).name());
915 * Returns a string describing this charset. </p>
917 * @return A string describing this charset
919 public final String toString() {