在 InputStreamReader 中应手动指定字符集(如 UTF-8 或 GB18030),推荐使用 StandardCharsets.UTF_8 或 Charset.forName("GB18030"),避免依赖平台默认编码导致乱码;GBK 非标准名,建议优先用 GB18030。

在 InputStreamReader 中手动指定字符集(如 UTF-8 或 GBK),关键是在构造时传入对应的 Charset 对象或字符集名称字符串,而不是依赖平台默认编码。
使用 Charset 类指定(推荐)
这种方式类型安全、可读性强,且编译期就能检查字符集名是否合法:
-
UTF-8:
new InputStreamReader(inputStream, StandardCharsets.UTF_8) -
GBK:
new InputStreamReader(inputStream, Charset.forName("GBK"))或Charset.forName("GB18030")(更兼容,能覆盖 GBK)
使用字符集名称字符串指定
直接传字符串,简洁但运行时才校验,拼错会抛 UnsupportedEncodingException:
-
UTF-8:
new InputStreamReader(inputStream, "UTF-8") -
GBK:
new InputStreamReader(inputStream, "GBK")或"GB18030"
注意事项
避免不指定字符集——否则会调用 Charset.defaultCharset(),结果依赖运行环境,极易导致中文乱码;
GBK 不是标准 IANA 字符集名,部分旧版 JDK 可能不识别 "GBK",建议优先用 "GB18030";
如果输入流来自网络或文件,确保源头实际编码与指定一致,否则仍会解码错误。
完整示例
读取一个 UTF-8 编码的文本文件:
try (FileInputStream fis = new FileInputStream("data.txt");
InputStreamReader reader = new InputStreamReader(fis, StandardCharsets.UTF_8)) {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
}
读取 GB18030 编码的文件(兼容 GBK):
InputStreamReader reader = new InputStreamReader(fis, "GB18030");不复杂但容易忽略

















