Java中GBK转UTF-8的几种方法
在Java中,将GBK编码的字符串或字节流转换为UTF-8编码有几种常见方法:

字符串转换方法
public String convertGBKtoUTF8(String gbkStr) {
try {
// 将GBK字符串转换为字节数组
byte[] gbkBytes = gbkStr.getBytes("GBK");
// 将字节数组按UTF-8编码重新构造字符串
return new String(gbkBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
转换方法
import java.io.*;
public void convertGBKFileToUTF8(File inputFile, File outputFile) {
try (InputStreamReader reader = new InputStreamReader(
new FileInputStream(inputFile), "GBK");
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(outputFile), "UTF-8")) {
char[] buffer = new char[1024];
int length;
while ((length = reader.read(buffer)) != -1) {
writer.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
使用Charset类(Java 7+)
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public String convertWithCharset(String gbkStr) {
// 将GBK字符串转换为字节数组
byte[] gbkBytes = gbkStr.getBytes(Charset.forName("GBK"));
// 使用UTF-8编码创建新字符串
return new String(gbkBytes, StandardCharsets.UTF_8);
}
批量转换目录中的文件
import java.io.*;
import java.nio.file.*;
public void convertDirectoryGBKtoUTF8(String dirPath) {
try {
Files.walk(Paths.get(dirPath))
.filter(Files::isRegularFile)
.forEach(file -> {
try {
String content = new String(
Files.readAllBytes(file), "GBK");
Files.write(file, content.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
注意事项
- 确保输入确实是GBK编码,否则会出现乱码
- 处理文件时考虑使用缓冲流提高性能
- 对于大文件,建议使用流式处理而不是一次性读取全部内容
- 在Java 7及以上版本,推荐使用
StandardCharsets类而不是字符串形式的编码名称
方法可以根据具体需求选择使用,字符串转换适用于内存中的数据,文件转换适用于处理文件内容。

