码迷,mamicode.com
首页 > 编程语言 > 详细

java File_encoding属性

时间:2017-07-16 12:36:33      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:继承   oca   问题   设置   mic   大致   文件编码   文件的   sed   

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

技术分享

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

windows下通常是GBK. 指定编码方式也非常easy,  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属性

标签:继承   oca   问题   设置   mic   大致   文件编码   文件的   sed   

原文地址:http://www.cnblogs.com/yfceshi/p/7190046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!