Convert byte array To String via charset - Android java.lang

Android examples for java.lang:String Byte Array

Description

Convert byte array To String via charset

Demo Code

import android.annotation.TargetApi;
import android.os.Build;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

public class Main{

    public static String byteToString(byte[] data, Charset charset) {
        return byteToString(data, 0, data.length, charset);
    }/*from  w w  w .jav  a 2s. c  o m*/
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static String byteToString(byte[] data, int offset,
            int byteCount, Charset charset) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return new String(data, offset, byteCount, charset);
        } else {
            // see: http://stackoverflow.com/questions/7376724
            CharsetDecoder decoder = charset.newDecoder();
            CharBuffer charBuffer;
            try {
                charBuffer = decoder.decode(ByteBuffer.wrap(data, offset,
                        byteCount));
                return charBuffer.toString();
            } catch (Exception e) {
                return new String(data, offset, byteCount); // last-ditch effort - ignore the encoding
            }
        }
    }

}

Related Tutorials