Java ByteBuffer from String toByteBuffer(String value)

Here you can find the source of toByteBuffer(String value)

Description

Convert the given String to a byte[] value using UTF-8 and wrap in a ByteBuffer.

License

Apache License

Parameter

Parameter Description
value String value.

Return

UTF-8 converted value wrapped in a ByteBuffer.

Declaration

public static ByteBuffer toByteBuffer(String value) 

Method Source Code

//package com.java2s;
/*/*from  w  w w . jav  a2s  .c  o 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 String to a byte[] value using UTF-8 and wrap in a ByteBuffer.
     * 
     * @param value String value.
     * @return      UTF-8 converted value wrapped in a ByteBuffer.
     */
    public static ByteBuffer toByteBuffer(String value) {
        return ByteBuffer.wrap(toBytes(value));
    }

    /**
     * Convert the given string to a byte[] in using the {@link #UTF8_CHARSET} encoder.
     * This is the inverse of {@link #toString(byte[])}. A null value is allowed, which
     * begets a null result.
     *
     * @param str   String value to be converted.
     * @return      Lossless, encoded value as a byte[], or null if str is null.
     */
    public static byte[] toBytes(String str) {
        if (str == null) {
            return null;
        }
        //optimization for ascii strings
        byte[] ascii = toAsciiBytes(str);
        if (ascii != null)
            return ascii;

        ByteBuffer bb = UTF8_CHARSET.encode(str);
        return getBytes(bb);
    }

    /**
     * Convert a long to a byte[] using the format Cassandra wants for a column or
     * supercolumn name. The antimethod for this one is {@link #toLong(byte[])}.
     *
     * @param value Long value to be converted.
     * @return      Same value encoded into an byte[8] array.
     */
    public static byte[] toBytes(long value) {
        byte[] bytes = new byte[8];
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.putLong(value);
        return bytes;
    }

    private static byte[] toAsciiBytes(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) > 127)
                return null;
        }
        byte[] bytes = new byte[str.length()];
        for (int i = 0; i < str.length(); i++) {
            bytes[i] = (byte) str.charAt(i);
        }
        return bytes;
    }

    /**
     * Extract the bytes in the given ByteBuffer and return it as a byte[]. CAUTION: this
     * method calls ByteBuffer.get(), which <i>transfers</i> bytes from the ByteBuffer to
     * the result buffer. Hence, it is "destructive" in the sense that the value cannot be
     * examined again without calling ByteBuffer.rewind() or something else. 
     *
     * @param   bytes   ByteBuffer.
     * @return          Contents between 'position' and 'limit' (aka 'remaining') as a
     *                  byte[].
     * @see     #copyBytes(ByteBuffer)
     */
    public static byte[] getBytes(ByteBuffer bytes) {
        byte[] result = new byte[bytes.remaining()]; // bytes between position and limit
        bytes.get(result);
        return result;
    }
}

Related

  1. stringToByteBuffer(String string)
  2. stringToNullTerminatedByteBuffer(String s)
  3. toByteBuffer(final String s)
  4. toByteBuffer(String hexStr)
  5. toByteBuffer(String s)
  6. toByteBuffer(String value)
  7. toByteBuffer(String value, String charsetName)