java File_encoding属性

时间:2014-07-12 21:03:22   收藏:0   阅读:156
今天给客户发版本,突然发现报表导出内容为空,大小0字节.感到非常奇怪,因为开发的时候都好好的,打包出来怎么会出现异常. 细看才后发现是 file_encoding这个java系统属性编码方式设置导致的. 开发的时候一般我们都在eclipse中把项目的 text file  encoding 这个属性设置为utf-8. 如图:

bubuko.com,布布扣

开发完,脱离eclipse之后我们同样需要指定该编码方式去执行java程序, 否则 当你输出System.getProperty("file.encoding")这个属性的时候,得到的结果就是系统默认的编码方式,

windows下一般是GBK. 指定编码方式也很简单,  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这个系统属性作为编码方式的,看代码:

		//way1
		String html1="<html>...</html>";
		FileWriter writer1=new FileWriter(new File("C:\\xxxx.html"));
		writer1.write(html1);
		writer1.close();
		
		//way2
		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.

2.JVM启动之前如果未指定file.encoding这个属性,这个属性就会默认为操作系统编码方式, JVM启动如果指定了file.encoding这个属性,整个项目都会用这个属性

作为reader和writer操作的默认编码方式.

so,解决问题最好的方式就是在启动项目时就知道file.encoding这个属性,后续的读写操作没有特殊编码需要的划,都可以继承过来使用.




java File_encoding属性,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!