Java Byte Array to String by Charset getChars(byte[] data, String charset)

Here you can find the source of getChars(byte[] data, String charset)

Description

get Chars

License

Open Source License

Declaration

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

Method Source Code

//package com.java2s;
/*//from w w  w. j  a  v a 2  s.  c  om
 * ====================================================================
 * 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;

public class Main {
    public static char[] getChars(byte[] data, String charset) {
        return getChars(data, 0, data != null ? data.length : 0, charset);
    }

    public static char[] getChars(byte[] data, int offset, int length, String charset) {
        if (data == null) {
            return new char[0];
        }
        Charset chrst;
        try {
            chrst = Charset.forName(charset);
        } catch (UnsupportedCharsetException e) {
            chrst = Charset.defaultCharset();
        }
        try {
            CharBuffer cb = chrst.newDecoder().decode(ByteBuffer.wrap(data, offset, length));
            final char[] chars = new char[cb.limit()];
            cb.get(chars);
            return chars;
        } catch (CharacterCodingException e) {
        }
        final char[] chars = new char[data.length];
        for (int i = 0; i < chars.length; i++) {
            chars[i] = (char) data[i];
        }
        return chars;
    }
}

Related

  1. getBytes(final String string, final Charset charset)
  2. getBytes(String string, Charset charset)
  3. getBytesByCharset(String str, Charset charset)
  4. getBytesUnchecked(String string, String charsetName)
  5. getBytesUnchecked(String string, String charsetName)
  6. getContentAsString(byte[] content, Charset charset)
  7. getMaxBytes(String string, int maxBytes, Charset charSet)
  8. getNumberOfBytesPerCharacter(final String charsetName)
  9. getPrefixWithMaxBytes(String string, int maxBytes, Charset charSet)