Java Convert via ByteBuffer toBytes(char[] ch)

Here you can find the source of toBytes(char[] ch)

Description

Converts a char array to a byte array.

License

Open Source License

Declaration

public static byte[] toBytes(char[] ch) 

Method Source Code


//package com.java2s;
/* Copyright (c) 2001 - 2013 OpenPlans - www.openplans.org. All rights reserved.
 * This code is licensed under the GPL 2.0 license, available at the root
 * application directory./*  w w  w  . j a va 2  s . c o  m*/
 */

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

public class Main {
    /**
     * Converts a char array to a byte array.
     * <p>
     * This method is unsafe since the charset is not specified, one of 
     * {@link #toBytes(char[], String)} or  {@link #toBytes(char[], Charset)} should be used 
     * instead. When not specified {@link Charset#defaultCharset()} is used.
     * </p>
     */
    public static byte[] toBytes(char[] ch) {
        return toBytes(ch, Charset.defaultCharset());
    }

    /**
     * Converts a char array to a byte array.
     */
    public static byte[] toBytes(char[] ch, String charset) {
        return toBytes(ch, Charset.forName(charset));
    }

    /**
     * Converts a char array to a byte array.
     */
    public static byte[] toBytes(char[] ch, Charset charset) {
        ByteBuffer buff = charset.encode(CharBuffer.wrap(ch));
        byte[] tmp = new byte[buff.limit()];
        buff.get(tmp);
        return tmp;
    }
}

Related

  1. toByteArray2(String filename)
  2. toByteArray3(String filename)
  3. toByteArrayFromInt(int intValue, boolean shortSize)
  4. toByteArrayFromLong(long longValue)
  5. toBytes(BigDecimal number, int byteLength)
  6. toBytes(char[] chars)
  7. toBytes(char[] string)
  8. toBytes(final float val)
  9. toBytes(final UUID uuid)