一,知道字符串编码的情况下
String s1 = "hello中国人";
String iso = new String(s1.getBytes("utf-8"), "iso-8859-1");System.out.println(iso);//helloä¸å›½äºº
String utf8 = new String(iso.getBytes("iso-8859-1"), "utf-8");
System.out.println(utf8);//hello中国人
String s1 = "hello中国人";
String gbk = new String(s1.getBytes("utf-8"), "gbk");
System.out.println(gbk);//hello涓浗浜�
String utf8 = new String(gbk.getBytes("gbk"), "utf-8");
System.out.println(utf8);//hello中国�?
二,不知道字符串编码的情况下,先获得字符串编码,然后再转编码
在Java中,String的getBytes()方法是得到一个操作系统默认的编码格式的字节数组。
而与getBytes相对的,可以通过new String(byte[], decode)的方式来还原字符串,
String的getBytes()方法是得到一个系统默认的编码格式的字节数组
getBytes("utf-8") 得到一个UTF-8格式的字节数组
三,获取字符串编码:
public class test {
public String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
// String str= "hello中国人";
// // 将字符串str转成 GB2312编码格式 赋给str1
// String str1 = new String(str.getBytes(encode),encode);
// // 如果str仍然等于str1,那么就可以确定str就是 encode格式
// if(str.equals(str1)){
// return encode;
// }
String s = encode;
return s;
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return "";
}
}