Java上传文件到Linux,显示乱码解决方法

在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.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章