// 将 Java String 转换为 byte 数组的示例代码
public class StringToByteExample {
public static void main(String[] args) {
// 定义一个字符串
String str = "Hello, World!";
// 使用getBytes()方法将字符串转换为字节数组,默认使用平台默认字符集
byte[] bytes = str.getBytes();
// 输出字节数组的内容
System.out.print("Bytes: ");
for (byte b : bytes) {
System.out.print(b + " ");
}
// 如果需要指定字符集,可以传递字符集名称作为参数
try {
byte[] utf8Bytes = str.getBytes("UTF-8");
System.out.println("\nUTF-8 Bytes: " + Arrays.toString(utf8Bytes));
byte[] isoBytes = str.getBytes("ISO-8859-1");
System.out.println("ISO-8859-1 Bytes: " + Arrays.toString(isoBytes));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
str
。getBytes()
方法将字符串转换为字节数组。如果不指定字符集,则使用平台默认字符集。getBytes()
方法来指定转换时使用的字符集。如果指定的字符集不受支持,则会抛出 UnsupportedEncodingException
异常。上一篇:java tcp通信
下一篇:java继承类怎么写
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站