How to convert byte to String?

 In Java, converting a byte array to a string (String) usually requires specifying a character encoding, because bytes can represent various character encodings, such as UTF-8, UTF-16, ISO-8859-1 wait. Here's an example of converting a byte array to a string, using UTF-8 character encoding:

public class ByteToStringExample {
    public static void main(String[] args) {
        try {
            // 创建一个字节数组
            byte[] byteArray = { 72, 101, 108, 108, 111 }; // 这个字节数组表示 "Hello"

            // 将字节数组转换为字符串,使用UTF-8字符编码
            String str = new String(byteArray, "UTF-8");

            // 打印结果
            System.out.println(str); // 输出 "Hello"
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

  In the above code, we first create a byteArray, where each byte represents a character in the string "Hello". We then convert the byte array to a string using new String(byteArray, "UTF-8") . Here "UTF-8" is the character encoding, which tells Java how to interpret the bytes in the byte array to build the string.

  Please note that if we are not sure which character encoding was used to generate the bytes in the byte array, using the wrong character encoding may cause garbled characters or wrong results. Therefore, it is very important to ensure that the correct character encoding is used.

  If the bytes in the byte array represent valid UTF-8 encoded character sequences, usually we can safely use the UTF-8 character encoding to convert the byte array to a string. However, if we have special requirements or are not sure about the character encoding, it is recommended to specify the exact character encoding when dealing with byte-to-string conversion.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/132555491