java怎么GB18030编码转UTF-8
时间: 2024-05-07 09:19:34 浏览: 12
Java中可以使用 `java.nio.charset.Charset` 类来进行编码转换。下面是一个将 GB18030 编码转换为 UTF-8 编码的示例代码:
```java
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.io.UnsupportedEncodingException;
public class GB18030toUTF8Converter {
public static void main(String[] args) {
String gb18030Str = "你好,世界!";
try {
// 将 GB18030 编码的字符串转换为字节数组
byte[] gb18030Bytes = gb18030Str.getBytes("GB18030");
// 将字节数组按 UTF-8 编码转换为字符串
String utf8Str = new String(gb18030Bytes, StandardCharsets.UTF_8);
System.out.println("GB18030 编码的字符串:" + gb18030Str);
System.out.println("转换为 UTF-8 编码的字符串:" + utf8Str);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们首先将 GB18030 编码的字符串转换为字节数组,然后再将字节数组按 UTF-8 编码转换为字符串。需要注意的是,如果字符串本身就是 UTF-8 编码的,则直接将其转换为字节数组即可,不需要进行编码转换。