Java ByteBuffer store String by Charset

Description

Java ByteBuffer store String by Charset

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;

public class Main {
  public static void main(String[] argv) {
    ByteBuffer buf = ByteBuffer.allocate(20);
    putCharSequence(buf, Charset.defaultCharset(), "demo2s.com");
    buf.flip();/* ww w  .  jav a2  s.  c om*/
    System.out.println(Arrays.toString(toArray(buf)));
  }

  public static void putCharSequence(ByteBuffer buf, Charset charset, CharSequence value) {
    putCharSequence(buf, charset.newEncoder(), value);
  }

  public static void putCharSequence(ByteBuffer buf, CharsetEncoder encoder, CharSequence value) {
    //
    // Convert any CharSequence implementor (String, etc) into a native
    // C string.
    //
    encoder.reset().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)
        .encode(CharBuffer.wrap(value), buf, true);
    encoder.flush(buf);
    final int nulSize = Math.round(encoder.maxBytesPerChar());
    // NUL terminate the string
    if (nulSize == 4) {
      buf.putInt(0);
    } else if (nulSize == 2) {
      buf.putShort((short) 0);
    } else if (nulSize == 1) {
      buf.put((byte) 0);
    }
  }

  public static byte[] toArray(final ByteBuffer buffer) {
    byte[] array = new byte[buffer.limit()];
    buffer.get(array);
    return array;
  }
}



PreviousNext

Related