判断字符串的编码格式
public static String detectEncoding(String str) {
Charset charset = StandardCharsets.UTF_8; // 默认UTF-8编码
if (charset.newEncoder().canEncode(str)) {
return "UTF-8";
}
charset = Charset.forName("GBK"); // GBK编码
if (charset.newEncoder().canEncode(str)) {
return "GBK";
}
return "UTF-8";
}
将字符串转换为UTF-8编码
public static String convertToUTF8(String str, String encoding) {
byte[] byteArray;
try {
byteArray = str.getBytes(encoding);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return new String(byteArray, StandardCharsets.UTF_8);
}