// 将 byte 数组转换为 String 的示例代码
public class ByteToStringExample {
public static void main(String[] args) {
// 定义一个 byte 数组
byte[] byteArray = {72, 101, 108, 108, 111}; // 对应 "Hello" 的 ASCII 值
// 使用构造函数将 byte 数组转换为 String,默认使用平台的默认字符集
String str1 = new String(byteArray);
System.out.println("Using default charset: " + str1);
// 指定字符集(例如 UTF-8)进行转换
try {
String str2 = new String(byteArray, "UTF-8");
System.out.println("Using UTF-8 charset: " + str2);
} catch (Exception e) {
e.printStackTrace();
}
// 如果只有一个 byte,可以这样转换
byte singleByte = 72; // 对应 'H'
String str3 = new String(new byte[]{singleByte});
System.out.println("Single byte to string: " + str3);
}
}
new String(byte[]) 构造函数可以直接将字节数组转换为字符串,默认情况下会使用平台的默认字符集。"UTF-8")来确保正确解码字节数据。byte 转换为字符串,可以将其封装为一个长度为 1 的字节数组,然后使用相同的构造函数。如果你有任何问题或需要进一步的帮助,请告诉我!
下一篇:java线程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站