Java ByteBuffer to String bufferToString(ByteBuffer buf)

Here you can find the source of bufferToString(ByteBuffer buf)

Description

buffer To String

License

Open Source License

Declaration

public static String bufferToString(ByteBuffer buf) 

Method Source Code

//package com.java2s;
/* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */

import java.io.UnsupportedEncodingException;

import java.nio.ByteBuffer;

public class Main {
    public static String bufferToString(ByteBuffer buf) {
        try {// ww  w .  jav a  2s .c o  m
            boolean isString = true;
            byte[] arr = buf.array();
            for (int i = 0; i < buf.remaining(); i++) {
                byte c = arr[i];
                if (c <= 127 || ((c & 0xC0) == 0x80) || ((c & 0xE0) == 0xC0))
                    continue;
                isString = false;
                break;
            }
            if (isString) {
                return new String(buf.array(), 0, buf.remaining(), "UTF-8");
            } else {
                StringBuilder sbuf = new StringBuilder();
                sbuf.append("byte[] bytes = new byte[] {");
                for (int i = 0; i < buf.remaining(); i++) {
                    if (i != 0)
                        sbuf.append(", ");
                    if ((i % 10) == 0)
                        sbuf.append("\r\n");
                    sbuf.append("(byte)0x");
                    int c = arr[i] & 0xFF;
                    String s = Integer.toHexString(c);
                    if (s.length() < 2)
                        sbuf.append("0");
                    sbuf.append(s);
                }
                sbuf.append("};");
                return sbuf.toString();
            }
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }
}

Related

  1. asString(ByteBuffer buffer, int length)
  2. asString(final ByteBuffer buffer)
  3. asString(Map headers)
  4. bbToString(ByteBuffer bb)
  5. buffer2String(ByteBuffer buff, String charsetName)
  6. bufferToString(ByteBuffer buf)
  7. bufferToString(ByteBuffer buff)
  8. bufferToString(ByteBuffer buffer)
  9. byteBufferToString(ByteBuffer buf)