Java ByteBuffer to Byte Array toByteArray(ByteBuffer bytes)

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

Description

Copies the byte buffer's content to a newly allocated byte array.

License

Open Source License

Declaration

public static byte[] toByteArray(ByteBuffer bytes) 

Method Source Code


//package com.java2s;
/*//  ww w . j a va  2s  .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");

    /**
     * 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. toByteArray(ByteBuffer buffer)
  2. toByteArray(ByteBuffer buffer)
  3. toByteArray(ByteBuffer buffer)
  4. toByteArray(ByteBuffer buffer, int length)
  5. toByteArray(ByteBuffer buffer, int length)
  6. toByteArrayByByteBuffer(int value)
  7. toBytes(ByteBuffer buff)
  8. toBytes(ByteBuffer buffer)
  9. toBytes(ByteBuffer buffer)