Example #1
0
  /**
   * Convert the char array to byte array with respect to given charset.
   *
   * @param charArray
   * @param strCharset null or "" means default charset
   * @exception CharacterCodingException
   */
  public static byte[] convertCharArrayToByteArray(char[] charArray, String strCharset)
      throws CharacterCodingException {

    if (charArray == null) {
      return null;
    }

    char[] cArray = (char[]) charArray.clone();
    CharBuffer charBuffer = CharBuffer.wrap(cArray);
    Charset charSet;
    if (strCharset == null || "".equals(strCharset)) {
      charSet = Charset.defaultCharset();
    } else if (Charset.isSupported(strCharset)) {
      charSet = Charset.forName(strCharset);
    } else {
      CharacterCodingException e = new CharacterCodingException();
      e.initCause(new UnsupportedCharsetException(strCharset));
      throw e;
    }

    CharsetEncoder encoder = charSet.newEncoder();
    ByteBuffer byteBuffer = null;
    try {
      byteBuffer = encoder.encode(charBuffer);
    } catch (CharacterCodingException cce) {
      throw cce;
    } catch (Throwable t) {
      CharacterCodingException e = new CharacterCodingException();
      e.initCause(t);
      throw e;
    }

    byte[] result = new byte[byteBuffer.remaining()];
    byteBuffer.get(result);
    clear(byteBuffer);
    clear(charBuffer);

    return result.clone();
  }
Example #2
0
  /**
   * Convert the byte array to char array with respect to given charset.
   *
   * @param byteArray
   * @param charset null or "" means default charset
   * @exception CharacterCodingException
   */
  public static char[] convertByteArrayToCharArray(byte[] byteArray, String charset)
      throws CharacterCodingException {

    if (byteArray == null) {
      return null;
    }

    byte[] bArray = (byte[]) byteArray.clone();
    ByteBuffer byteBuffer = ByteBuffer.wrap(bArray);
    Charset charSet;
    if (charset == null || "".equals(charset)) {
      charSet = Charset.defaultCharset();
    } else if (Charset.isSupported(charset)) {
      charSet = Charset.forName(charset);
    } else {
      CharacterCodingException e = new CharacterCodingException();
      e.initCause(new UnsupportedCharsetException(charset));
      throw e;
    }

    CharsetDecoder decoder = charSet.newDecoder();
    CharBuffer charBuffer = null;
    try {
      charBuffer = decoder.decode(byteBuffer);
    } catch (CharacterCodingException cce) {
      throw cce;
    } catch (Throwable t) {
      CharacterCodingException e = new CharacterCodingException();
      e.initCause(t);
      throw e;
    }
    char[] result = (char[]) charBuffer.array().clone();
    clear(byteBuffer);
    clear(charBuffer);

    return result;
  }