Java ByteBuffer to String toString(ByteBuffer bytes)

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

Description

Parses a string out of a byte buffer whose content is UTF-8 encoded.

License

Open Source License

Declaration

public static String toString(ByteBuffer bytes) 

Method Source Code


//package com.java2s;
/*//from  w w  w .ja  v a 2  s  . c o m
 * This file is part of Multimap.  http://multimap.io
 *
 * Copyright (C) 2015-2016  Martin Trenkmann
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

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

public class Main {
    /**
     * An UTF-8 charset constant used for encoding/decoding strings to/from byte arrays.
     */
    public static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * Parses a string out of a byte buffer whose content is UTF-8 encoded.
     */
    public static String toString(ByteBuffer bytes) {
        return toString(toByteArray(bytes));
    }

    /**
     * Parses a string out of a byte array whose content is UTF-8 encoded.
     */
    public static String toString(byte[] bytes) {
        return new String(bytes, UTF8);
    }

    /**
     * Copies the byte buffer's content to a newly allocated byte array.
     */
    public static byte[] toByteArray(ByteBuffer bytes) {
        byte[] array = new byte[bytes.capacity()];
        bytes.get(array);
        return array;
    }

    /**
     * Serializes the string's content to an UTF-8 encoded byte array.
     */
    public static byte[] toByteArray(String string) {
        return string.getBytes(UTF8);
    }
}

Related

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