public class GetBytesExample {
public static void main(String[] args) {
// 定义一个字符串
String str = "Hello, Java!";
// 使用默认字符集将字符串转换为字节数组
byte[] bytes = str.getBytes();
// 输出字节数组的内容
for (byte b : bytes) {
System.out.print(b + " ");
}
// 使用指定字符集将字符串转换为字节数组
try {
byte[] utf8Bytes = str.getBytes("UTF-8");
System.out.println("\nUTF-8编码的字节数组:");
for (byte b : utf8Bytes) {
System.out.print(b + " ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
str.getBytes()
:使用默认字符集(通常是平台的默认字符集)将字符串转换为字节数组。str.getBytes("UTF-8")
:使用指定的字符集(如 UTF-8)将字符串转换为字节数组。如果指定了无效的字符集名称,会抛出 UnsupportedEncodingException
异常,因此需要捕获异常。希望这个示例代码和解释对你有帮助!
上一篇:java jar运行
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站