Here you can find the source of getBytes(final char[] data, String charset)
public static byte[] getBytes(final char[] data, String charset)
//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'); } }