1. 程式人生 > >Java字串編碼轉換UTF-8

Java字串編碼轉換UTF-8

import java.io.UnsupportedEncodingException;

/**
 * 
 * 
 * 描述:<p>    功能描述,該部分必須以中文句號結尾。</p>
 * 建立日期:2012-7-16 下午4:28:16<br>
 * @author:tianyj<br> 
 * @update:$Date$<br>
 * @version:$Revision$<br>
 * @since 版本號,用來指定該類是從整個專案的哪個版本開始加入到專案中的
 */
public class ConvertCharSet {

	private static String changeCharSet(
			String str, String newCharset) throws UnsupportedEncodingException {
		if (str != null) {
			// 用預設字元編碼解碼字串。
			byte[] bs = str.getBytes();
			// 用新的字元編碼生成字串
			return new String(bs, newCharset);
		}
		return str;
	}
	
	/**
	 * 字串轉化為UTF-8
	 * @param str
	 * @return
	 */
	public static String toUTF8(String str){
		String result = str;
		try {
	        result = changeCharSet(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
        }
		return result;
	}
	
	/**
	 * 位元組陣列轉化為UTF-8
	 * @param bty
	 * @return
	 */
	public static String toUTF8(byte[] bty){
		try {
	        if (bty.length > 0) {
	        	return new String(bty, "UTF-8");
	        }
        } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
        }
		return new String(bty);
	}
}