java.nio.charset

## Class CharsetDecoder

- java.lang.Object
- - java.nio.charset.CharsetDecoder

-     public abstract class CharsetDecoder
      extends Object

  An engine that can transform a sequence of bytes in a specific charset into a sequence of sixteen-bit Unicode characters.

  The input byte sequence is provided in a byte buffer or a series of such buffers. The output character sequence is written to a character buffer or a series of such buffers. A decoder should always be used by making the following sequence of method invocations, hereinafter referred to as a decoding operation:

  1. Reset the decoder via the `reset` method, unless it has not been used before;

  2. Invoke the `decode` method zero or more times, as long as additional input may be available, passing `false` for the `endOfInput` argument and filling the input buffer and flushing the output buffer between invocations;

  3. Invoke the `decode` method one final time, passing `true` for the `endOfInput` argument; and then

  4. Invoke the `flush` method so that the decoder can flush any internal state to the output buffer.

  Each invocation of the `decode` method will decode as many bytes as possible from the input buffer, writing the resulting characters to the output buffer. The `decode` method returns when more input is required, when there is not enough room in the output buffer, or when a decoding error has occurred. In each case a `CoderResult` object is returned to describe the reason for termination. An invoker can examine this object and fill the input buffer, flush the output buffer, or attempt to recover from a decoding error, as appropriate, and try again.

  There are two general types of decoding errors. If the input byte sequence is not legal for this charset then the input is considered malformed. If the input byte sequence is legal but cannot be mapped to a valid Unicode character then an unmappable character has been encountered.

  How a decoding error is handled depends upon the action requested for that type of error, which is described by an instance of the `CodingErrorAction` class. The possible error actions are to ``ignore`` the erroneous input, ``report`` the error to the invoker via the returned `CoderResult` object, or ``replace`` the erroneous input with the current value of the replacement string. The replacement has the initial value `"\uFFFD"`; its value may be changed via the `replaceWith` method.

  The default action for malformed-input and unmappable-character errors is to ``report`` them. The malformed-input error action may be changed via the `onMalformedInput` method; the unmappable-character action may be changed via the `onUnmappableCharacter` method.

  This class is designed to handle many of the details of the decoding process, including the implementation of error actions. A decoder for a specific charset, which is a concrete subclass of this class, need only implement the abstract `decodeLoop` method, which encapsulates the basic decoding loop. A subclass that maintains internal state should, additionally, override the `implFlush` and `implReset` methods.

  Instances of this class are not safe for use by multiple concurrent threads.

  Since:
    1.4
  Author:
    Mark Reinhold, JSR-51 Expert Group
  See Also:
    `ByteBuffer`, `CharBuffer`, `Charset`, `CharsetEncoder`

- - ### Constructor Summary

    Constructors
    Modifier | Constructor and Description
    --- | ---
    `protected` | `CharsetDecoder(Charset cs, float averageCharsPerByte, float maxCharsPerByte)` Initializes a new decoder.

  - ### Method Summary

    All Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `float` | `averageCharsPerByte()` Returns the average number of characters that will be produced for each byte of input.
    `Charset` | `charset()` Returns the charset that created this decoder.
    `Charset` | `detectedCharset()` Retrieves the charset that was detected by this decoder (optional operation).
    `protected void` | `implReplaceWith(String newReplacement)` Reports a change to this decoder's replacement value.
    `protected void` | `implReset()` Resets this decoder, clearing any charset-specific internal state.
    `boolean` | `isAutoDetecting()` Tells whether or not this decoder implements an auto-detecting charset.
    `boolean` | `isCharsetDetected()` Tells whether or not this decoder has yet detected a charset (optional operation).
    `float` | `maxCharsPerByte()` Returns the maximum number of characters that will be produced for each byte of input.
    `String` | `replacement()` Returns this decoder's replacement value.
    `CharsetDecoder` | `replaceWith(String newReplacement)` Changes this decoder's replacement value.
    `CharsetDecoder` | `reset()` Resets this decoder, clearing any internal state.

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Constructor Detail

    - #### CharsetDecoder

          protected CharsetDecoder(Charset cs,
                                   float averageCharsPerByte,
                                   float maxCharsPerByte)

      Initializes a new decoder. The new decoder will have the given chars-per-byte values and its replacement will be the string `"\uFFFD"`.
      Parameters:
        `averageCharsPerByte` - A positive float value indicating the expected number of characters that will be produced for each input byte
        `maxCharsPerByte` - A positive float value indicating the maximum number of characters that will be produced for each input byte
      Throws:
        `IllegalArgumentException` - If the preconditions on the parameters do not hold

  - ### Method Detail

    - #### charset

          public final Charset charset()

      Returns the charset that created this decoder.
      Returns:
        This decoder's charset

    - #### replacement

          public final String replacement()

      Returns this decoder's replacement value.
      Returns:
        This decoder's current replacement, which is never `null` and is never empty

    - #### replaceWith

          public final CharsetDecoder replaceWith(String newReplacement)

      Changes this decoder's replacement value.

      This method invokes the `implReplaceWith` method, passing the new replacement, after checking that the new replacement is acceptable.

      Parameters:
        `newReplacement` - The new replacement; must not be `null` and must have non-zero length
      Returns:
        This decoder
      Throws:
        `IllegalArgumentException` - If the preconditions on the parameter do not hold

    - #### implReplaceWith

          protected void implReplaceWith(String newReplacement)

      Reports a change to this decoder's replacement value.

      The default implementation of this method does nothing. This method should be overridden by decoders that require notification of changes to the replacement.

      Parameters:
        `newReplacement` -

    - #### averageCharsPerByte

          public final float averageCharsPerByte()

      Returns the average number of characters that will be produced for each byte of input. This heuristic value may be used to estimate the size of the output buffer required for a given input sequence.
      Returns:
        The average number of characters produced per byte of input

    - #### maxCharsPerByte

          public final float maxCharsPerByte()

      Returns the maximum number of characters that will be produced for each byte of input. This value may be used to compute the worst-case size of the output buffer required for a given input sequence.
      Returns:
        The maximum number of characters that will be produced per byte of input

    - #### reset

          public final CharsetDecoder reset()

      Resets this decoder, clearing any internal state.

      This method resets charset-independent state and also invokes the `implReset` method in order to perform any charset-specific reset actions.

      Returns:
        This decoder

    - #### implReset

          protected void implReset()

      Resets this decoder, clearing any charset-specific internal state.

      The default implementation of this method does nothing. This method should be overridden by decoders that maintain internal state.

    - #### isAutoDetecting

          public boolean isAutoDetecting()

      Tells whether or not this decoder implements an auto-detecting charset.

      The default implementation of this method always returns `false`; it should be overridden by auto-detecting decoders to return `true`.

      Returns:
        `true` if, and only if, this decoder implements an auto-detecting charset

    - #### isCharsetDetected

          public boolean isCharsetDetected()

      Tells whether or not this decoder has yet detected a charset (optional operation).

      If this decoder implements an auto-detecting charset then at a single point during a decoding operation this method may start returning `true` to indicate that a specific charset has been detected in the input byte sequence. Once this occurs, the `detectedCharset` method may be invoked to retrieve the detected charset.

      That this method returns `false` does not imply that no bytes have yet been decoded. Some auto-detecting decoders are capable of decoding some, or even all, of an input byte sequence without fixing on a particular charset.

      The default implementation of this method always throws an `UnsupportedOperationException`; it should be overridden by auto-detecting decoders to return `true` once the input charset has been determined.

      Returns:
        `true` if, and only if, this decoder has detected a specific charset
      Throws:
        `UnsupportedOperationException` - If this decoder does not implement an auto-detecting charset

    - #### detectedCharset

          public Charset detectedCharset()

      Retrieves the charset that was detected by this decoder (optional operation).

      If this decoder implements an auto-detecting charset then this method returns the actual charset once it has been detected. After that point, this method returns the same value for the duration of the current decoding operation. If not enough input bytes have yet been read to determine the actual charset then this method throws an `IllegalStateException`.

      The default implementation of this method always throws an `UnsupportedOperationException`; it should be overridden by auto-detecting decoders to return the appropriate value.

      Returns:
        The charset detected by this auto-detecting decoder, or `null` if the charset has not yet been determined
      Throws:
        `IllegalStateException` - If insufficient bytes have been read to determine a charset
        `UnsupportedOperationException` - If this decoder does not implement an auto-detecting charset

Copyright © 2025 API Design. All Rights Reserved.