CharsetDecoderTest.java

import java.nio.*;
import java.nio.charset.*;
class CharsetDecoderTest {
  public static void main(String[] args) {
    Charset charset = Charset.forName("ASCII");
    CharsetDecoder decoder = charset.newDecoder();
    byte[] tab = {(byte)'c',(byte)'r',(byte)'é',(byte)'é'};
    ByteBuffer byteB = ByteBuffer.wrap(tab);
    byteB.limit(1);
    CharBuffer charB = CharBuffer.allocate(tab.length);
    // decoder.reset(); // Inutile car juste alloué

    // Décodage du premier caractère
    CoderResult cr = decoder.decode(byteB,charB,false);
    System.out.println(cr);             // Affiche UNDERFLOW
    charB.flip();
    System.out.println(charB);          // Affiche c
    charB.position(charB.limit());
    charB.limit(charB.capacity());
    byteB.limit(byteB.capacity());
    
    // Décodage du reste des caractères
    decoder.onMalformedInput(CodingErrorAction.REPLACE);
    decoder.replaceWith("*");
    cr = decoder.decode(byteB,charB,true);
    decoder.flush(charB);
    charB.flip();
    System.out.println(charB);          // Affiche cr**
  }
}