Java Convert via ByteBuffer toByteArray(String value)

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

Description

Encodes the given string in UTF-8.

License

Apache License

Parameter

Parameter Description
value the string to encode.

Return

a newly allocated array containing the encoding result.

Declaration

public static byte[] toByteArray(String value) 

Method Source Code

//package com.java2s;
/*//from   w  w w. j a v  a 2  s .c o m
 * Copyright 2013-2016 Guardtime, Inc.
 *
 * This file is part of the Guardtime client SDK.
 *
 * 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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 * "Guardtime" and "KSI" are trademarks or registered trademarks of
 * Guardtime, Inc., and no license to trademarks is granted; Guardtime
 * reserves and retains all trademark rights.
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;

public class Main {
    /**
     * The default buffer size for the data read/copy operations in this class.
     */
    public static final int DEFAULT_BUFFER_SIZE = 8192;

    /**
     * Encodes the given string in UTF-8.
     *
     * @param value
     *         the string to encode.
     * @return a newly allocated array containing the encoding result.
     */
    public static byte[] toByteArray(String value) {
        if (value == null) {
            return null;
        }
        try {
            CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder()
                    .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
            ByteBuffer buf = encoder.encode(CharBuffer.wrap(value));
            // don't use ByteBuffer.array(), as it returns internal, and
            // possibly larger, byte array
            byte[] res = new byte[buf.remaining()];
            buf.get(res);
            return res;
        } catch (CharacterCodingException e) {
            throw new RuntimeException("Unexpected exception", e);
        }
    }

    /**
     * Copies all available data from {@code in} to byte array.
     *
     * @param in
     *         input stream to copy data from.
     * @return array of bytes read from input stream
     * @throws IOException
     */
    public static byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        copyData(in, out);
        return out.toByteArray();
    }

    /**
     * Copies all available data from {@code in} to byte array.
     *
     * @param in
     *         input stream to copy data from.
     * @param bufferSize
     *         buffer size to use
     * @return array of bytes read from input stream
     * @throws IOException
     */
    public static byte[] toByteArray(InputStream in, int bufferSize) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        copyData(in, out, bufferSize);
        return out.toByteArray();
    }

    /**
     * Converts {@code value} to two-byte array.
     * <p/>
     * Bytes are returned in network byte order (ordered from the most to the least significant byte).
     *
     * @param value
     *         the value to convert.
     * @return the converted bytes as an array.
     */
    public static byte[] toByteArray(short value) {
        return new byte[] { (byte) (value >>> 8), (byte) value };
    }

    /**
     * Converts {@code value} to four-byte array.
     * <p/>
     * Bytes are returned in network byte order (ordered from the most to the least significant byte).
     *
     * @param value
     *         the value to convert.
     * @return the converted bytes as an array.
     */
    public static byte[] toByteArray(int value) {
        return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value };
    }

    /**
     * Converts {@code value} to eight-byte array.
     * <p/>
     * Bytes are returned in network byte order (ordered from the most to the least significant byte).
     *
     * @param value
     *         the value to convert.
     * @return the converted bytes as an array.
     */
    public static byte[] toByteArray(long value) {
        return new byte[] { (byte) (value >>> 56), (byte) (value >>> 48), (byte) (value >>> 40),
                (byte) (value >>> 32), (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8),
                (byte) value };
    }

    /**
     * Copies all available data from {@code in} to {@code out}.
     * <p/>
     * Allocates a temporary memory buffer of {@link #DEFAULT_BUFFER_SIZE} bytes for this.
     *
     * @param in
     *         input stream to copy data from.
     * @param out
     *         output stream to copy data to.
     * @return the number of bytes actually copied.
     * @throws IOException
     *         if one is thrown by either {@code in} or {@code out}.
     */
    public static int copyData(InputStream in, OutputStream out) throws IOException {
        return copyData(in, out, -1, DEFAULT_BUFFER_SIZE);
    }

    /**
     * Copies up to {@code limit} bytes of data from {@code in} to {@code out}.
     * <p/>
     * May copy less than {@code limit} bytes if {@code in} does not have that much data available.
     * <p/>
     * Allocates a temporary memory buffer of {@code bufSize} bytes for this.
     *
     * @param in
     *         input stream to copy data from.
     * @param out
     *         output stream to copy data to.
     * @param limit
     *         maximum number of bytes to copy ({@code -1} to copy all bytes).
     * @param bufSize
     *         size of the buffer to allocate (larger buffer may speed up the process).
     * @return the number of bytes actually copied.
     * @throws IOException
     *         if one is thrown by either {@code in} or {@code out}.
     */
    public static int copyData(InputStream in, OutputStream out, int limit, int bufSize) throws IOException {

        if (bufSize < 1) {
            throw new IllegalArgumentException("Invalid buffer size: " + bufSize);
        }

        byte[] buf = new byte[bufSize];
        int total = 0;
        while (limit < 0 || total < limit) {
            int maxRead = ((limit < 0) ? buf.length : Math.min(limit - total, buf.length));
            int count = in.read(buf, 0, maxRead);
            if (count < 1) {
                break;
            }
            out.write(buf, 0, count);
            total += count;
        }
        return total;
    }

    /**
     * Copies up to {@code limit} bytes of data from {@code in} to {@code out}.
     * <p/>
     * May copy less than {@code limit} bytes if {@code in} does not have that much data available.
     * <p/>
     * Allocates a temporary memory buffer of {@link #DEFAULT_BUFFER_SIZE} bytes for this.
     *
     * @param in
     *         input stream to copy data from.
     * @param out
     *         output stream to copy data to.
     * @param limit
     *         maximum number of bytes to copy.
     * @return the number of bytes actually copied.
     * @throws IOException
     *         if one is thrown by either {@code in} or {@code out}.
     */
    public static int copyData(InputStream in, OutputStream out, int limit) throws IOException {
        return copyData(in, out, limit, DEFAULT_BUFFER_SIZE);
    }
}

Related

  1. toByteArray(long[] data)
  2. ToByteArray(long[] data)
  3. toByteArray(ReadableByteChannel channel)
  4. toByteArray(String bits)
  5. ToByteArray(String hexString)
  6. toByteArray(UUID uniqueId)
  7. toByteArray2(String filename)
  8. toByteArray3(String filename)
  9. toByteArrayFromInt(int intValue, boolean shortSize)