Java ByteBuffer to String toString(ByteBuffer bytes)

Here you can find the source of toString(ByteBuffer bytes)

Description

Extract the byte[] within the given ByteBuffer and decode into a String using UTF-8.

License

Apache License

Parameter

Parameter Description
bytes ByteBuffer object.

Return

Internal byte[] value converted to a String using UTF-8.

Declaration

public static String toString(ByteBuffer bytes) 

Method Source Code

//package com.java2s;
/*//from  ww  w .  j  ava 2  s . co m
 * Copyright (C) 2014 Dell, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    /**
     * The Charset object for the UTF-8 character set.
     */
    public static final Charset UTF8_CHARSET = Charset.forName("UTF-8");

    /**
     * Convert the given byte[] to a String using the {@link #UTF8_CHARSET} decoder. This
     * is the inverse of {@link #toBytes(String)}. As with that method, null begets null.
     *
     * @param bytes A byte[] representing a String value.
     * @return      The decoded String value, or null if null is given.
     */
    public static String toString(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        //optimization for ASCII string
        String ascii = toAsciiString(bytes);
        if (ascii != null)
            return ascii;

        return new String(bytes, UTF8_CHARSET);
    }

    /**
     * Extract the byte[] within the given ByteBuffer and decode into a String using UTF-8.
     * This method calls {@link #copyBytes(ByteBuffer)}, which examines the ByteBuffer
     * without side-effects, therefore allowing it to be read again.
     * 
     * @param bytes ByteBuffer object.
     * @return      Internal byte[] value converted to a String using UTF-8.
     */
    public static String toString(ByteBuffer bytes) {
        return toString(copyBytes(bytes));
    }

    /**
     * Convert the a subset of given byte[] starting at index 'offset' for 'length' bytes
     * to a String using the reverse process used by {@link #toBytes(String)}. As with
     * that method, null begets null.
     *
     * @param bytes     Byte[] to convert.
     * @param offset    Index of first byte to convert.
     * @param length    Number of bytes to convert.
     * @return          Decoded string, or null if null is given.
     */
    public static String toString(byte[] bytes, int offset, int length) {
        if (bytes == null) {
            return null;
        }
        //optimization for ASCII string
        String ascii = toAsciiString(bytes, offset, length);
        if (ascii != null)
            return ascii;

        return new String(bytes, offset, length, UTF8_CHARSET);
    }

    private static String toAsciiString(byte[] bytes) {
        for (int i = 0; i < bytes.length; i++) {
            if (bytes[i] < 0)
                return null;
        }
        char[] chars = new char[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            chars[i] = (char) bytes[i];
        }
        return new String(chars);
    }

    private static String toAsciiString(byte[] bytes, int offset, int length) {
        for (int i = 0; i < length; i++) {
            if (bytes[offset + i] < 0)
                return null;
        }
        char[] chars = new char[length];
        for (int i = 0; i < length; i++) {
            chars[i] = (char) bytes[offset + i];
        }
        return new String(chars);
    }

    /**
     * Extract the bytes in the given ByteBuffer and return it as a byte[] without
     * affecting the mark, position, or limit of the given buffer. This method should be
     * used instead of {@link #getBytes(ByteBuffer)} when the ByteBuffer might be re-read
     * again.
     *
     * @param   bytes   ByteBuffer.
     * @return          Contents between 'position' and 'limit' (aka 'remaining') as a
     *                  byte[]. Parameter object is unaffected.
     */
    public static byte[] copyBytes(ByteBuffer bytes) {
        ByteBuffer copy = bytes.duplicate();
        byte[] result = new byte[copy.remaining()]; // bytes between position and limit
        copy.get(result);
        return result;
    }
}

Related

  1. toString(ByteBuffer buffer)
  2. toString(ByteBuffer buffer, Charset charset)
  3. toString(ByteBuffer buffer, int offset, int length)
  4. toString(ByteBuffer buffer, String encoding)
  5. toString(ByteBuffer bytes)
  6. toString(ByteBuffer sequence)
  7. toString(ByteBuffer value, String charsetName)
  8. toString(final ByteBuffer buffer)
  9. toString(final ByteBuffer buffer)