utf8 unicode java_Java实现的utf8,gbk,unicode编码相互转换的代码
时间: 2024-02-20 20:00:29 浏览: 82
以下是 Java 实现的 utf8,gbk,unicode 编码相互转换的代码:
```java
import java.io.UnsupportedEncodingException;
public class EncodingUtil {
public static String utf8ToUnicode(String str) {
try {
byte[] bytes = str.getBytes("UTF-8");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.length; i += 2) {
builder.append("\\u");
String hexStr = Integer.toHexString(bytes[i + 1] & 0xff | (bytes[i] & 0xff) << 8);
if (hexStr.length() == 2) {
builder.append("00");
}
builder.append(hexStr);
}
return builder.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String unicodeToUtf8(String str) {
StringBuilder builder = new StringBuilder();
int i = 0;
while (i < str.length()) {
if (str.charAt(i) == '\\' && str.charAt(i + 1) == 'u') {
String hexStr = str.substring(i + 2, i + 6);
int codePoint = Integer.parseInt(hexStr, 16);
builder.append((char) codePoint);
i += 6;
} else {
builder.append(str.charAt(i));
i++;
}
}
try {
return new String(builder.toString().getBytes("UTF-8"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String gbkToUtf8(String str) {
try {
return new String(str.getBytes("GBK"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String utf8ToGbk(String str) {
try {
return new String(str.getBytes("UTF-8"), "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String unicodeToGbk(String str) {
return utf8ToGbk(unicodeToUtf8(str));
}
public static String gbkToUnicode(String str) {
return utf8ToUnicode(gbkToUtf8(str));
}
}
```
其中,`utf8ToUnicode` 方法将 utf8 编码的字符串转换为 unicode 编码的字符串,`unicodeToUtf8` 方法将 unicode 编码的字符串转换为 utf8 编码的字符串,`gbkToUtf8` 方法将 gbk 编码的字符串转换为 utf8 编码的字符串,`utf8ToGbk` 方法将 utf8 编码的字符串转换为 gbk 编码的字符串,`unicodeToGbk` 方法将 unicode 编码的字符串转换为 gbk 编码的字符串,`gbkToUnicode` 方法将 gbk 编码的字符串转换为 unicode 编码的字符串。
阅读全文