java.nio.charset

## Class CharsetEncoder

- java.lang.Object
- - java.nio.charset.CharsetEncoder

-     public abstract class CharsetEncoder
      extends Object

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

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

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

  2. Invoke the `encode` 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 `encode` method one final time, passing `true` for the `endOfInput` argument; and then

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

  Each invocation of the `encode` method will encode as many characters as possible from the input buffer, writing the resulting bytes to the output buffer. The `encode` method returns when more input is required, when there is not enough room in the output buffer, or when an encoding 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 an encoding error, as appropriate, and try again.

  There are two general types of encoding errors. If the input character sequence is not a legal sixteen-bit Unicode sequence then the input is considered malformed. If the input character sequence is legal but cannot be mapped to a valid byte sequence in the given charset then an unmappable character has been encountered.

  How an encoding 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 byte array. The replacement is initially set to the encoder's default replacement, which often (but not always) has the initial value `{` `(byte)'?'` `}`; 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 encoding process, including the implementation of error actions. An encoder for a specific charset, which is a concrete subclass of this class, need only implement the abstract `encodeLoop` method, which encapsulates the basic encoding 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`, `CharsetDecoder`

- - ### Constructor Summary

    Constructors
    Modifier | Constructor and Description
    --- | ---
    `protected` | `CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar)` Initializes a new encoder.
    `protected` | `CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement)` Initializes a new encoder.

  - ### Method Summary

    All Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `float` | `averageBytesPerChar()` Returns the average number of bytes that will be produced for each character of input.
    `Charset` | `charset()` Returns the charset that created this encoder.
    `protected void` | `implReplaceWith(byte[] newReplacement)` Reports a change to this encoder's replacement value.
    `protected void` | `implReset()` Resets this encoder, clearing any charset-specific internal state.
    `float` | `maxBytesPerChar()` Returns the maximum number of bytes that will be produced for each character of input.
    `byte[]` | `replacement()` Returns this encoder's replacement value.
    `CharsetEncoder` | `replaceWith(byte[] newReplacement)` Changes this encoder's replacement value.
    `CharsetEncoder` | `reset()` Resets this encoder, clearing any internal state.

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

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

- - ### Constructor Detail

    - #### CharsetEncoder

          protected CharsetEncoder(Charset cs,
                                   float averageBytesPerChar,
                                   float maxBytesPerChar,
                                   byte[] replacement)

      Initializes a new encoder. The new encoder will have the given bytes-per-char and replacement values.
      Parameters:
        `averageBytesPerChar` - A positive float value indicating the expected number of bytes that will be produced for each input character
        `maxBytesPerChar` - A positive float value indicating the maximum number of bytes that will be produced for each input character
        `replacement` - The initial replacement; must not be `null`, must have non-zero length, must not be longer than maxBytesPerChar, and must be ``legal``
      Throws:
        `IllegalArgumentException` - If the preconditions on the parameters do not hold

    - #### CharsetEncoder

          protected CharsetEncoder(Charset cs,
                                   float averageBytesPerChar,
                                   float maxBytesPerChar)

      Initializes a new encoder. The new encoder will have the given bytes-per-char values and its replacement will be the byte array `{` `(byte)'?'` `}`.
      Parameters:
        `averageBytesPerChar` - A positive float value indicating the expected number of bytes that will be produced for each input character
        `maxBytesPerChar` - A positive float value indicating the maximum number of bytes that will be produced for each input character
      Throws:
        `IllegalArgumentException` - If the preconditions on the parameters do not hold

  - ### Method Detail

    - #### charset

          public final Charset charset()

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

    - #### replacement

          public final byte[] replacement()

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

    - #### replaceWith

          public final CharsetEncoder replaceWith(byte[] newReplacement)

      Changes this encoder'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`, must have non-zero length, must not be longer than the value returned by the `maxBytesPerChar` method, and must be ``legal``
      Returns:
        This encoder
      Throws:
        `IllegalArgumentException` - If the preconditions on the parameter do not hold

    - #### implReplaceWith

          protected void implReplaceWith(byte[] newReplacement)

      Reports a change to this encoder's replacement value.

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

      Parameters:
        `newReplacement` -

    - #### averageBytesPerChar

          public final float averageBytesPerChar()

      Returns the average number of bytes that will be produced for each character 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 bytes produced per character of input

    - #### maxBytesPerChar

          public final float maxBytesPerChar()

      Returns the maximum number of bytes that will be produced for each character 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 bytes that will be produced per character of input

    - #### reset

          public final CharsetEncoder reset()

      Resets this encoder, 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 encoder

    - #### implReset

          protected void implReset()

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

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

Copyright © 2025 API Design. All Rights Reserved.