Convert the content of a byte buffer to a string - Java java.nio

Java examples for java.nio:ByteBuffer Convert

Description

Convert the content of a byte buffer to a string

Demo Code


//package com.java2s;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import java.nio.charset.Charset;

public class Main {
    /**//from   w w w.  ja v  a2  s.  c om
     *  Convert the content of a byte buffer to a string
     *  @param buf is the byte buffer
     *  @param charset indicates the character set encoding
     *  @return a string
     */
    public static String stringFromBuffer(ByteBuffer buf, Charset charset) {
        CharBuffer cb = charset.decode(buf.duplicate());
        return (cb.toString());
    }

    /**
     *  Convert the content of a byte buffer to a string, using a
     *  default char encoding
     *  @param buf is the byte buffer
     *  @return a string
     */
    public static String stringFromBuffer(ByteBuffer buf) {
        Charset charset = Charset.forName("UTF-8");
        return (stringFromBuffer(buf, charset));
    }

    /**
     * Print a byte array as a String
     */
    public static String toString(byte[] bytes) {

        StringBuilder sb = new StringBuilder(4 * bytes.length);
        sb.append("[");

        for (int i = 0; i < bytes.length; i++) {
            sb.append(unsignedByteToInt(bytes[i]));
            if (i + 1 < bytes.length) {
                sb.append(",");
            }
        }

        sb.append("]");
        return sb.toString();
    }

    /**
     * Convert an unsigned byte to an int
     */
    public static int unsignedByteToInt(byte b) {
        return (int) b & 0xFF;
    }
}

Related Tutorials