byte[] byteArray = {72, 101, 108, 108, 111}; // 对应于 "Hello"
String str = new String(byteArray);
System.out.println(str); // 输出: Hello
2. 使用`String`类的`getBytes()`方法:
byte[] byteArray = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}; // 对应于 "Hello World"
String str = new String(byteArray, StandardCharsets.UTF_8);
byte[] byteArray2 = str.getBytes(StandardCharsets.UTF_8);
System.out.println(Arrays.equals(byteArray, byteArray2)); // 输出: true
3. 使用Base64编码:
import java.util.Base64;
byte[] byteArray = {72, 101, 108, 108, 111}; // 对应于 "Hello"
String str = new String(Base64.getEncoder().encode(byteArray));
System.out.println(str); // 输出: SGVsbG8=
4. 使用`Charset`类指定字符集:
byte[] byteArray = {72, 101, 108, 108, 111}; // 对应于 "Hello"
String str = new String(byteArray, Charset.forName("UTF-8"));
System.out.println(str); // 输出: Hello
以上方法都可以将字节数组转换为对应的字符串。选择哪种方法取决于你的具体需求,比如是否需要指定字符集或者是否需要进行Base64编码