Java Byte Array to String by Charset getBytes(final char[] data, String charset)

Here you can find the source of getBytes(final char[] data, String charset)

Description

get Bytes

License

Open Source License

Declaration

public static byte[] getBytes(final char[] data, String charset) 

Method Source Code

//package com.java2s;
/*/*  w ww  . j  a v  a  2 s .com*/
 * ====================================================================
 * Copyright (c) 2004-2012 TMate Software Ltd.  All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.  The terms
 * are also available at http://svnkit.com/license.html
 * If newer versions of this license are posted there, you may use a
 * newer version instead, at your option.
 * ====================================================================
 */

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;

public class Main {
    public static byte[] getBytes(final char[] data, String charset) {
        if (data == null) {
            return new byte[0];
        }
        final CharBuffer cb = CharBuffer.wrap(data);
        Charset chrst;
        try {
            chrst = Charset.forName(charset);
        } catch (UnsupportedCharsetException e) {
            chrst = Charset.defaultCharset();
        }
        try {
            ByteBuffer bb = chrst.newEncoder().encode(cb);
            final byte[] bytes = new byte[bb.limit()];
            bb.get(bytes);
            if (bb.hasArray()) {
                clearArray(bb.array());
            }
            return bytes;
        } catch (CharacterCodingException e) {
        }

        final byte[] bytes = new byte[data.length];
        for (int i = 0; i < data.length; i++) {
            bytes[i] = (byte) (data[i] & 0xFF);
        }
        return bytes;
    }

    public static void clearArray(byte[] array) {
        if (array == null) {
            return;
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = 0;
        }
        Arrays.fill(array, (byte) 0xFF);
    }

    public static void clearArray(char[] array) {
        if (array == null) {
            return;
        }
        Arrays.fill(array, '\0');
    }
}

Related

  1. decodeWithReplacement(byte[] bytes, Charset cs)
  2. encode(byte[] arr, Charset srcCharset, Charset dstCharset)
  3. encodeB(String prefix, String text, int usedCharacters, Charset charset, byte[] bytes)
  4. encodingIsCorrect(byte[] bytes, String charset)
  5. getAverageBytesPerCharacter(Charset charset)
  6. getBytes(final String string, final Charset charset)
  7. getBytes(String string, Charset charset)
  8. getBytesByCharset(String str, Charset charset)
  9. getBytesUnchecked(String string, String charsetName)