在 java 中,使用 new string(byte[] bytes, charset charset) 构造函数可以指定编码格式对字节数组进行解码。调用时传入原始字节流和目标字符集对象(如 standardcharsets.utf_8),该方法会立即将字节转换为字符串,若字节序列不符合指定编码规范则抛出 malformedinputexception。

new String() 如何指定 UTF-8 编码
通过传入 java.nio.charset.StandardCharsets.UTF_8 常量,可以将字节数组按 UTF-8 规则解析为 Unicode 字符串。这种方式避免了检查异常,且性能优于传递字符串名称的方式。

import java.nio.charset.StandardCharsets;
public class DecodeExample {
public static void main(String[] args) {
byte[] data = {72, 101, 108, 108, 111}; // "Hello"
String result = new String(data, StandardCharsets.UTF_8);
System.out.println(result); // 输出: Hello
}
}
new String() 处理 ISO-8859-1 编码
当需要兼容旧系统或二进制传输协议时,常使用 ISO-8859-1 编码。该编码将每个字节直接映射为一个 Unicode 码位,适合用于字节与字符的一一对应转换场景。
立即学习“Java免费学习笔记(深入)”;

import java.nio.charset.StandardCharsets;
public class IsoDecode {
public static void main(String[] args) {
byte[] raw = {(byte) 0xE9}; // Latin Small Letter E With Acute
String s = new String(raw, StandardCharsets.ISO_8859_1);
System.out.println(s); // 输出: é
}
}
指定编码时遇到非法字节序列会发生什么
如果输入的字节序列不符合指定的编码规则(例如 UTF-8 中出现非法起始字节),new String() 构造函数会抛出 MalformedInputException。这是严格模式下的行为,确保数据完整性。


















