寫 Java 程式時經常會用到 Properties 檔存放 Message 等資訊,但打開來看到的往往是一堆看不懂的編碼。原因是 Java 編譯器與其他 Java 工具只能處理 Latin-1 與/或 Unicode 編碼(\udddd 形式)的檔案,因此像 Struts 這類框架的範例資源檔,都會先經過 Unicode 編碼處理。以下整理兩種做法。
功能:把含本地編碼字元(既非 Latin1 也非 Unicode)的檔案,轉換為 Unicode 編碼字元的檔案。
語法:native2ascii [options] [inputfile [outputfile]]
補充:若省略 outputfile,結果輸出到標準輸出裝置;若同時省略 inputfile,則從標準輸入裝置讀入。
常用選項:
應用範例:
native2ascii -encoding GBK ApplicationResources.properties ApplicationResources_zh_CN.properties
我的操作步驟是:先把存放英文的 ApplicationResource.properties 複製一份並改名為 a(純粹為了縮短 DOS 指令長度);用編輯器在 a 裡寫入中文;最後在 DOS 視窗切到該目錄執行:
native2ascii a ApplicationResource_zh.properties
如果不方便開命令列,也可以直接在瀏覽器裡完成轉換。原理是利用 escape() 把非 ASCII 字元編碼成 %XX 形式,再把 % 換成 / 作為暫存佔位,反向操作時再還原。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>ASC←→NATIVE 轉換工具</TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<script language="javascript">
function native2ascii(){
var regexp = /[^\x00-\xff]/g;
var n = document.getElementById("native").value;
var a = n;
while(m = regexp.exec(n)){
a = a.split(m[0]).join(escape(m[0]).split("%").join("/"));
}
document.getElementById("ascii").value = a;
}
function ascii2native(){
var a = document.getElementById("ascii").value;
var n = unescape(a.split("/").join("%"));
document.getElementById("native").value = n;
}
</script>
</HEAD>
<BODY>
<h1>ASC←→NATIVE 轉換工具</h1>
代碼 :<br>
<textarea id="ascii" rows="10" cols="100"></textarea><br>
漢字:<input type="button" id="back" value="代碼→漢字 ↓↓↓" onclick="ascii2native()"/>
<input type="button" id="convert" value="漢字→代碼 ↑↑↑" onclick="native2ascii()"/>
<br>
<textarea id="native" rows="10" cols="100"></textarea>
</BODY>
</HTML>
用 /[^\x00-\xff]/g 抓出所有非單位元組字元,就是中文等非 ASCII 字元;escape 後的 %uXXXX 再把 % 替換成 / 避免與 URL 編碼混淆,反向時還原即可。這個工具雖然簡單,處理日常 Properties 檔的編碼問題已經夠用。