java跟python类似的做法,在java中字符串的编码是java修改过的一种Unicode编码,所以看到java中的字符串,心理要默念这个东西是java修改过的一种Unicode编码的编码。
packagestring;importjava.nio.charset.Charset;public classUTF82GBK {public static void main(String[] args) throwsException {//系统的默认编码是GBK
System.out.println("Default Charset=" +Charset.defaultCharset());
String t= "hfjkds中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国中国hfsdkj fjldsajflkdsjaflkdsjalf sfdsfadas";//思路:先转为Unicode,然后转为GBK
String utf8 = new String(t.getBytes( "UTF-8"));//等同于://String utf8 = new String(t.getBytes( "UTF-8"),Charset.defaultCharset());
System.out.println(utf8);
String unicode= new String(utf8.getBytes(),"UTF-8");//等同于://String unicode = new String(utf8.getBytes(Charset.defaultCharset()),"UTF-8");
System.out.println(unicode);
String gbk= new String(unicode.getBytes("GBK"));//等同于://String gbk = new String(unicode.getBytes("GBK"),Charset.defaultCharset());
System.out.println(gbk);
}
}
packagecom.mkyong;importjava.io.BufferedReader;importjava.io.File;importjava.io.FileInputStream;importjava.io.InputStreamReader;public classUTF8ToGBK {public static void main(String[] args) throwsException {
File fileDir= new File("/home/user/Desktop/Unsaved Document 1");
BufferedReader in= new BufferedReader(newInputStreamReader(new FileInputStream(fileDir), "UTF-8"));
String str;while ((str = in.readLine()) != null) {
System.out.println(str);//java内部只有unicode编码 所以str是unicode编码
String str2 = new String(str.getBytes("GBK"), "GBK");//str.getBytes("GBK")是gbk编码,但是str2是unicode编码
System.out.println(str2);
}
in.close();
}
}
问题的关键是new String(xxx.getBytes("gbk"), "gbk")这句话是什么意思,xxx.getBytes("gbk")得到的数组编码是GBK,因此必须必须告诉java:我传给你的数组是gbk编码的,你在转换成你内部的编码的时候记得要进行一些处理,new String(xxx.getBytes("gbk"), "gbk"),这句话第二个“gbk”是告诉java传递给它的是gbk编码的字符串。
String fullStr = new String(str.getBytes("UTF-8"), "UTF-8");//正常
String fullStr2 = new String(str.getBytes("UTF-8"), "GBK");//不正常,java内置的编码->utf8 被当成GBK编码转换成java内置的编码
看一下jdk文档是怎么说的
public String(byte[] bytes,
Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.
那现在的问题就是,我怎么在String中持有GBK编码的东西呢?
String str3 = new String(str.getBytes("GBK"),"ISO-8859-1");
System.out.println(new String(str3.getBytes("ISO-8859-1"),"GBK"));