練功房推薦書單

  • 黑心建商的告白:買屋前不看會哭的17堂課
  • 黑心房仲的告白:買屋簽約前最後救命的17堂課
  • 黑心投資客炒房告白:搞懂中古屋坑錢陷阱的17堂課
  • 猛虎出閘制霸版:最新OCP Java SE 6 Programmer專業認證(附原始程式碼及範例檔)
如何只將Big5不支援的UTF-8碼轉為HTML Entity  XML
Forum Index » 網頁程式設計 Web Development
Author Message
andowson

六段學員
[Avatar]

Joined: 2007-01-02 22:20:40
Messages: 662
Location: 台北
Offline

有些資料庫使用Big5編碼,遇到Big5字集外的UTF-8中文字元時,可以採用將該字元轉換為&#xxxxx;格式,再跟原字串合併儲存,例如當字串變數str="中文喆堃"時,後面兩個中文字不在Big5字集的範圍內,我們希望將其轉為
"中文喆堃"這樣子的結果。

底下是範例程式
UTF8ToBig5.java:
package com.andowson.chinese;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class UTF8ToBig5 {

	public static String convertHtml(String str) {
		StringBuilder buf = new StringBuilder(str.length());
		CharsetEncoder enc = Charset.forName("Big5").newEncoder();
		for (int idx = 0; idx < str.length(); idx++) {
			char ch = str.charAt(idx);
			if (enc.canEncode(ch)) {
				buf.append(ch);
			} else {
				buf.append("&#").append((int)ch).append(';');
			}
		}		 
		return buf.toString();		
	}
	
	/**
	 * @param args	  
	 */
	public static void main(String[] args) {
		String str = "中文喆堃";
		String result = convertHtml(str);
		System.out.println(result);		
	}

}


參考資料:
http://stackoverflow.com/questions/1760766/how-to-convert-non-supported-character-to-html-entity-in-java
 Filename UTF8ToBig5.java [Disk] Download
 Description UTF8ToBig5.java
 Filesize 736 bytes
 Downloaded:  2 time(s)


分享經驗 累積智慧
[WWW] [MSN]
 
Forum Index » 網頁程式設計 Web Development
Go to: