在windows系統下 默認編碼是GBK/GB2312的編碼格式,linux上默認爲utf-8的編碼格式。
當我們在windows上上傳文件的時候,JVM會根據本身的操作系統所默認的編碼格式 編譯成unicode字節數組,進行存儲。
然後解析的時候也會根據本身的操作系統默認的編碼格式進行解析。
上傳文件中文亂碼時: JVM編譯成gbk格式的unicode字節數組,然後解析成utf-8的格式,所以導致亂碼。
亂碼的本質是: 字符串原本的編碼格式 和 讀取解析的編碼格式不一致 所造成的 。
在java中使用 new String(bytes,charset); 方法可以解決亂碼問題。
bytes :表示編譯採用什麼格式進行編譯 ,charset : 表示使用什麼格式進行解析
在windows上 如:
String str="我很帥哦";
System.out.println(new String(str.getBytes(),"gbk")); 是正確的
System.out.println(new String(str.getBytes("utf-8"),"utf-8")); 也是正確的
System.out.println(new String(str.getBytes("gbk"),"utf-8")); 是錯誤的
那麼 如何將GBK 轉化成utf-8呢? (實際上是unicode轉成utf-8)
byte[] utfbytes=str.getBytes("utf-8");
String strFinsh=new String (utfbytes,"utf-8");
簡寫:System.out.println(new String(str.getBytes("utf-8"),"utf-8"));
utf-8轉成gbk 也是一樣的
new String(str.getBytes("gbk"),"gbk");
getBytes(charset)
在JDK中這樣描述的:Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.