標籤:繼承 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這個系統屬性作為編碼方式的,看代碼:
//way1String html1="<html>...</html>";FileWriter writer1=new FileWriter(new File("C:\\xxxx.html"));writer1.write(html1);writer1.close();//way2String 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屬性