Used to verify the encoding of a byte array. - Java java.lang

Java examples for java.lang:byte Array Bit Operation

Description

Used to verify the encoding of a byte array.

Demo Code


//package com.java2s;

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

public class Main {
    /**/* ww  w . j  av  a2  s . co m*/
     * 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 Tutorials