您的位置:首页 > 运维架构 > Linux

java上传文件到linux上 防止文件名中文乱码

2017-12-23 15:04 791 查看
在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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息