// 示例代码:将 byte 数组转换为 String
public class ByteToStringExample {
public static void main(String[] args) {
// 定义一个 byte 数组
byte[] byteArray = {72, 101, 108, 108, 111}; // 对应 "Hello" 的 ASCII 码
// 使用 String 构造函数将 byte 数组转换为字符串,默认使用平台的默认字符集
String str = new String(byteArray);
// 输出转换后的字符串
System.out.println("转换后的字符串: " + str);
// 如果需要指定字符集,可以传递字符集名称作为第二个参数
try {
String strWithCharset = new String(byteArray, "UTF-8");
System.out.println("使用 UTF-8 字符集转换后的字符串: " + strWithCharset);
} catch (Exception e) {
e.printStackTrace();
}
}
}
byte[] byteArray = {72, 101, 108, 108, 111}; 这里定义了一个包含 ASCII 码值的 byte 数组,对应的字符是 "Hello"。new String(byteArray) 将 byte 数组转换为字符串,默认使用平台的默认字符集(通常是 UTF-8 或 ISO-8859-1)。new String(byteArray, "UTF-8") 允许你显式指定字符集,确保在不同平台上的一致性。上一篇:java optional用法
下一篇:java post请求
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站