Convert remaining ByteBuffer to UTF-8 String. - Java java.nio

Java examples for java.nio:ByteBuffer Convert

Description

Convert remaining ByteBuffer to UTF-8 String.

Demo Code

/*//from ww w .  ja  v  a2 s  . c  om
 * WireSpider
 *
 * Copyright (c) 2015 kazyx
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */
//package com.java2s;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * Convert remaining byte buffer to UTF-8 String.
     *
     * @param bytes Source byte buffer.
     * @return String expression of the bytes.
     */
    public static String toTextRemaining(ByteBuffer bytes) {
        return new String(toBytesRemaining(bytes), UTF8);
    }

    /**
     * Convert remaining byte buffer to byte array.
     *
     * @param buffer Source byte buffer
     * @return Remaining byte array.
     */
    public static byte[] toBytesRemaining(ByteBuffer buffer) {
        byte[] array = new byte[buffer.remaining()];
        buffer.get(array);
        return array;
    }
}

Related Tutorials