import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
public class StringToByteStream {
public static void main(String[] args) {
String str = "Hello, World!";
// 方法1: 使用StandardCharsets类
byte[] bytes1 = str.getBytes(StandardCharsets.UTF_8);
// 方法2: 显式使用UTF-8编码
try {
byte[] bytes2 = str.getBytes("UTF-8");
// 打印字节数组以验证转换
System.out.println("Bytes using StandardCharsets: " + bytesToHex(bytes1));
System.out.println("Bytes using UTF-8 encoding: " + bytesToHex(bytes2));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// 辅助方法:将字节数组转换为十六进制字符串
private static String bytesToHex(byte[] bytes) {
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
hex.append(String.format("%02X ", b));
}
return hex.toString();
}
}
12-15
316
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-25
2510
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-22
2727
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)