Java Byte Array to String by Charset encodingIsCorrect(byte[] bytes, String charset)

Here you can find the source of encodingIsCorrect(byte[] bytes, String charset)

Description

Used to verify the encoding of a byte array.

License

Apache License

Parameter

Parameter Description
bytes the bytes to convert to string.
charset the charset to convert to

Return

true is the bytes can be encoded into this charset, and false otherwise

Declaration

public static boolean encodingIsCorrect(byte[] bytes, String charset) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.nio.*;
import java.nio.charset.*;

public class Main {
    /**//from   w  w w. j ava2 s .c om
     * Used to verify the encoding of a byte array. This method does not actually
     * convert to string; it merely checks to see if it is possible without errors.
     * @param bytes the bytes to convert to string.
     * @param charset the charset to convert to
     * @return true is the bytes can be encoded into this charset, and false otherwise
     */
    public static boolean encodingIsCorrect(byte[] bytes, String charset) {
        try {
            CharsetDecoder decoder = Charset.forName(charset).newDecoder();
            decoder.decode(ByteBuffer.wrap(bytes));
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}

Related

  1. decodeHelper(byte[] byteArray, int numberOfBytes, java.nio.charset.Charset charset)
  2. decodeOrDefault(byte[] data, Charset charset, String defaultValue)
  3. decodeWithReplacement(byte[] bytes, Charset cs)
  4. encode(byte[] arr, Charset srcCharset, Charset dstCharset)
  5. encodeB(String prefix, String text, int usedCharacters, Charset charset, byte[] bytes)
  6. getAverageBytesPerCharacter(Charset charset)
  7. getBytes(final char[] data, String charset)
  8. getBytes(final String string, final Charset charset)
  9. getBytes(String string, Charset charset)