How can Java convert a byte array into a string?

You can convert a byte array to a string using the constructor of the String class in Java. Here is the specific code:

byte[] byteArray = {97, 98, 99, 100, 101}; // 示例byte数组
String str = new String(byteArray);
System.out.println(str);

The output is:

abcde

When constructing a String object, you can choose to specify the encoding, for example:

byte[] byteArray = {97, 98, 99, 100, 101}; // 示例byte数组
String str = new String(byteArray, StandardCharsets.UTF_8); // 指定为UTF-8编码
System.out.println(str);

Please ensure that each element in the byte array is a valid character encoding value when converting a byte array to a string. Otherwise, there may be garbled text or issues with the conversion process.

bannerAds