Java Byte Array to String by Charset toChars(byte[] b, String charset)

Here you can find the source of toChars(byte[] b, String charset)

Description

Converts byte array to char array.

License

Open Source License

Declaration

public static char[] toChars(byte[] b, String charset) 

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.//ww w  .ja va2 s  . co  m
 */

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

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

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

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

Related

  1. parseBytes(byte[] encoded, Charset charset)
  2. str(byte[] bytes, String charset)
  3. stringToByteArray(String str, Charset charsetForEncoding, int lenOfByteArray, byte filler)
  4. toBytes(CharSequence str, String charsetName)
  5. toBytes(String string, Charset charset)
  6. toCharSet(byte[] bytes, String fromCharsetName, String toCharsetName)
  7. toDebugString(final byte[] bytes, final int len, final Charset charset)
  8. toEncodedString(byte[] bytes, Charset charset)
  9. toString(byte[] b, String charset)