设置-Dfile.encoding 解决 java项目乱码问题

  • 2016-06-08
  • 浏览 (2449)

今天遇到一个项目乱码的问题,整个项目都用了utf8编码,请求另外一个项目获取数据,那个项目也是utf8编码的,但显示的数据却乱码了,在网上找到了问题原因:

linux 系统默认编码utf-8。

WINDOWS 默认编码GBK。

在window中使用secureCRT经常会遇到乱码的问题,因为linux默认编码UFT-8,window中secureCRT默认编码是GBK,链接到linux系统就会出现乱码,所以把secureCRT的默认编码修改为utf-8就可以。

了解了系统平台的的编码,才容易解决编码问题。

tomcat的应用的编码是utf-8,在windows中应用输出采用系统默认编码GBK,所以乱码,在启动jvm时设置成 -Dfile.encoding="UTF-8",应用乱码问题解决。
 
部署在tomcat中的文件要修改file.encoding的值,可以在tomcat的catalina.bat文件中set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%的后面加上 -Dfile.encoding="UTF-8"

windows指定编码方式也很简单, java -Dfile.encoding=utf-8 xxxx (需要执行的class文件)
 
下面来看下 file.encoding 这个属性的英文解释:
 
This property is used for the default encoding in Java, all readers and writers would default to use this property. “file.encoding” is set to the default locale of Windows operationg system since Java 1.4.2. System.getProperty(“file.encoding”) can be used to access this property. Code such as System.setProperty(“file.encoding”, “UTF-8”) can be used to change this property. However, the default encoding can not be changed dynamically even this property can be changed. So the conclusion is that the default encoding can’t be changed after JVM starts. “java -Dfile.encoding=UTF-8” can be used to set the default encoding when starting a JVM. I have searched for this option Java official documentation. But I can’t find it.

大致的意思主要下面几点:
 
1、java内所有的 reader 和 writer 操作默认都是用 file.encoding 这个系统属性作为编码方式的,看代码:

String html1="<html>...</html>";  
FileWriter writer1=new FileWriter(new File("C:\\xxxx.html"));  
writer1.write(html1);  
writer1.close();  

String html2="<html>...</html>";  
OutputStreamWriter writer2=new OutputStreamWriter(new FileOutputStream(new File("C:\\xxxx.html")),"utf-8");
writer2.write(html2);  
writer2.close();

第一种方法默认会用 file.encoding 这个属性对文件进行编码,然后输出.一旦你执行class文件的时候没有指定该属性, 默认就会用操作系统本身编码方式,如gbk等。

第二种方式指定了文件编码方式,并输出,但是这只能解决这一地方,其他没发现的就不好解决了,解决方法看下面。
 
2、JVM启动之前如果未指定file.encoding这个属性,这个属性就会默认为操作系统编码方式, JVM启动如果指定了file.encoding这个属性,整个项目都会用这个属性作为reader和writer操作的默认编码方式,并且在一个运行的应用程序中
 
file.encoding的值只有一个,并且值为入口函数的保存编码的值,不会被后面的覆盖。所以解决问题最好的方式就是在启动项目时就设置file.encoding这个属性。


eclipse 设置 -Dfile.encoding="UTF-8" : run > Run Configurations... > Apache Tomcat > Tomcat vX > Arguments > VM arguments 添加  -Dfile.encoding="UTF-8"
1  赞