Java 中 GB2312 转 UTF-8 的方法
在 Java 中,将 GB2312 编码的字符串转换为 UTF-8 编码可以通过以下几种方式实现:

使用 String 构造方法
String gb2312String = "这是GB2312编码的字符串";
String utf8String = new String(gb2312String.getBytes("GB2312"), "UTF-8");
使用 Charset 类(Java 1.5+ 推荐)
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
String gb2312String = "这是GB2312编码的字符串";
byte[] gb2312Bytes = gb2312String.getBytes(Charset.forName("GB2312"));
String utf8String = new String(gb2312Bytes, StandardCharsets.UTF_8);
处理字节数组转换
如果需要处理字节数组而不是直接处理字符串:
// 假设 byte[] 是 GB2312 编码的字节数组
byte[] gb2312Bytes = {(byte)0xB9, (byte)0xE3}; // "中"的GB2312编码
// 转换为UTF-8字符串
String utf8String = new String(gb2312Bytes, "GB2312");
// 或者转换为UTF-8编码的字节数组
byte[] utf8Bytes = new String(gb2312Bytes, "GB2312").getBytes("UTF-8");
注意事项
-
异常处理:建议添加异常处理,因为指定的编码可能不被支持
try { String utf8String = new String(gb2312String.getBytes("GB2312"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } -
文件读写转换:如果是从文件读取GB2312编码内容并保存为UTF-8:
// 读取GB2312文件 BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream("input.txt"), "GB2312")); // 写入UTF-8文件 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("output.txt"), "UTF-8")); String line; while ((line = reader.readLine()) != null) { writer.write(line); } reader.close(); writer.close(); -
Web应用中:在Servlet中处理请求参数时:
(图片来源网络,侵删)request.setCharacterEncoding("GB2312"); String param = request.getParameter("name"); String utf8Param = new String(param.getBytes("ISO-8859-1"), "GB2312");
选择哪种方法取决于你的具体需求,但推荐使用 Charset 类的方法,因为它更现代且更不容易出错。

