Java ByteBuffer convert to String by Charset

Description

Java ByteBuffer convert to String by Charset

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer bb = ByteBuffer.wrap("demo2s.com".getBytes());

    System.out.println(Arrays.toString(toArray(bb)));
    bb.flip();//from   w  w w .  j a va2 s .co m
    CharSequence string = getCharSequence(bb, Charset.defaultCharset());
    System.out.println(string);
  }

  public static CharSequence getCharSequence(ByteBuffer buf, Charset charset) {
    final ByteBuffer buffer = buf.slice();
    // Find the NUL terminator and limit to that, so the
    // StringBuffer/StringBuilder does not have superfluous NUL chars
    int end = indexOf(buffer, (byte) 0);
    if (end < 0) {
      end = buffer.limit();
    }
    buffer.position(0).limit(end);
    return charset.decode(buffer);
  }

  public static int indexOf(ByteBuffer buf, byte value) {
    if (buf.hasArray()) {
      byte[] array = buf.array();
      int begin = buf.arrayOffset() + buf.position();
      int end = buf.arrayOffset() + buf.limit();
      for (int offset = 0; offset < end && offset > -1; ++offset) {
        if (array[begin + offset] == value) {
          return offset;
        }
      }
    } else {
      int begin = buf.position();
      for (int offset = 0; offset < buf.limit(); ++offset) {
        if (buf.get(begin + offset) == value) {
          return offset;
        }
      }
    }
    return -1;
  }

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



PreviousNext

Related