Java Utililty Methods Byte Array to String by Charset

List of utility methods to do Byte Array to String by Charset

Description

The list of methods to do Byte Array to String by Charset are organized into topic(s).

Method

StringdecodeWithReplacement(byte[] bytes, Charset cs)
decode With Replacement
CharsetDecoder decoder = cs.newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPLACE);
decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
try {
    return decoder.decode(ByteBuffer.wrap(bytes)).toString();
} catch (CharacterCodingException e) {
    return String.format("could not decode as %s", cs.displayName());
byte[]encode(byte[] arr, Charset srcCharset, Charset dstCharset)
encode
ByteBuffer inputBuffer = ByteBuffer.wrap(arr);
CharBuffer data = srcCharset.decode(inputBuffer);
ByteBuffer outputBuffer = dstCharset.encode(data);
byte[] outputData = outputBuffer.array();
return outputData;
StringencodeB(String prefix, String text, int usedCharacters, Charset charset, byte[] bytes)
encode B
int encodedLength = bEncodedLength(bytes);
int totalLength = prefix.length() + encodedLength + ENC_WORD_SUFFIX.length();
if (totalLength <= ENCODED_WORD_MAX_LENGTH - usedCharacters) {
    return prefix + encodeB(bytes) + ENC_WORD_SUFFIX;
} else {
    int splitOffset = text.offsetByCodePoints(text.length() / 2, -1);
    String part1 = text.substring(0, splitOffset);
    byte[] bytes1 = encode(part1, charset);
...
booleanencodingIsCorrect(byte[] bytes, String charset)
Used to verify the encoding of a byte array.
try {
    CharsetDecoder decoder = Charset.forName(charset).newDecoder();
    decoder.decode(ByteBuffer.wrap(bytes));
} catch (Exception e) {
    return false;
return true;
intgetAverageBytesPerCharacter(Charset charset)
Get the average number of bytes a character can consist of in the provided charset.
int avg = 0;
if (charset != null) {
    avg = Math.round(charset.newEncoder().averageBytesPerChar());
return avg;
byte[]getBytes(final char[] data, String charset)
get Bytes
if (data == null) {
    return new byte[0];
final CharBuffer cb = CharBuffer.wrap(data);
Charset chrst;
try {
    chrst = Charset.forName(charset);
} catch (UnsupportedCharsetException e) {
...
byte[]getBytes(final String string, final Charset charset)
Calls String#getBytes(Charset)
if (string == null) {
    return null;
return string.getBytes(charset);
byte[]getBytes(String string, Charset charset)
get Bytes
return string == null ? null : string.getBytes(charset);
byte[]getBytesByCharset(String str, Charset charset)
get Bytes By Charset
if (isNotBlank(str)) {
    return str.getBytes(charset);
return null;
byte[]getBytesUnchecked(String string, String charsetName)
Encodes the given string into a sequence of bytes using the named charset, storing the result into a new byte array.
if (string == null) {
    return null;
try {
    return string.getBytes(charsetName);
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    return null;
...