java跟python類似的做法,在java中字符串的編碼是java修改過的一種Unicode編碼,所以看到java中的字符串,心理要默念這個東西是java修改過的一種Unicode編碼的編碼。
package string; import java.nio.charset.Charset; public class UTF82GBK { public static void main(String[] args) throws Exception { //系統的默認編碼是GBK System.out.println("Default Charset=" + Charset.defaultCharset()); String t = "hfjkds中國中國中國中國中國中國中國中國中國中國中國中國中國中國中國中國中國中國中國中國hfsdkj<img src='sasa' /> fjldsajflkdsjaflkdsjalf <img src='sada' ait=''/>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); } }
package com.mkyong; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; public class UTF8ToGBK { public static void main(String[] args) throws Exception { File fileDir = new File("/home/user/Desktop/Unsaved Document 1"); BufferedReader in = new BufferedReader(new InputStreamReader( 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"));
