java后台如何转码
Java 后台转码方法
使用 String 类的构造函数
通过 String 的构造函数指定字符集进行转码,适用于字节数组到字符串的转换。
byte[] bytes = ...; // 原始字节数据
String str = new String(bytes, "UTF-8"); // 转为UTF-8字符串
byte[] newBytes = str.getBytes("GBK"); // 转为GBK字节数组
使用 Charset 类
Charset 类提供了更灵活的字符集处理方式,支持标准字符集名称。

import java.nio.charset.Charset;
byte[] bytes = ...;
Charset utf8Charset = Charset.forName("UTF-8");
Charset gbkCharset = Charset.forName("GBK");
String str = new String(bytes, utf8Charset); // UTF-8解码
byte[] newBytes = str.getBytes(gbkCharset); // GBK编码
处理URL编码/解码
使用 URLEncoder 和 URLDecoder 处理URL中的特殊字符。

import java.net.URLEncoder;
import java.net.URLDecoder;
String original = "测试&数据";
String encoded = URLEncoder.encode(original, "UTF-8"); // 编码
String decoded = URLDecoder.decode(encoded, "UTF-8"); // 解码
文件读写转码
通过 InputStreamReader 和 OutputStreamWriter 指定字符集读写文件。
import java.io.*;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("input.txt"), "ISO-8859-1"))) {
String line;
while ((line = reader.readLine()) != null) {
// 处理ISO-8859-1编码内容
}
}
处理Base64编码
使用 Base64 类进行二进制数据的Base64编解码。
import java.util.Base64;
byte[] data = ...;
String encoded = Base64.getEncoder().encodeToString(data); // 编码
byte[] decoded = Base64.getDecoder().decode(encoded); // 解码
注意事项
- 转码时需明确源数据的字符集,避免因误判导致乱码。
- 处理中文字符时优先使用
UTF-8或GBK等支持中文的字符集。 - 文件操作后需及时关闭流资源,推荐使用try-with-resources语法。






