// 将字符串转换为字节数组的示例代码
public class StringToByteExample {
public static void main(String[] args) {
// 定义一个字符串
String str = "Hello, Java!";
// 使用getBytes()方法将字符串转换为字节数组,默认使用平台默认字符集
byte[] bytes = str.getBytes();
// 输出字节数组的内容
System.out.print("字节数组内容: ");
for (byte b : bytes) {
System.out.print(b + " ");
}
System.out.println();
// 指定字符集进行转换,例如UTF-8
try {
byte[] utf8Bytes = str.getBytes("UTF-8");
System.out.print("UTF-8编码的字节数组内容: ");
for (byte b : utf8Bytes) {
System.out.print(b + " ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
str
,内容为 "Hello, Java!"
。getBytes()
方法将字符串转换为字节数组。如果不指定字符集,则会使用平台默认的字符集。"UTF-8"
)来指定使用的字符集进行转换,并输出相应的字节数组内容。如果需要处理其他字符集,可以替换 "UTF-8"
为其他字符集名称。
下一篇:java获取当天零点时间
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站