char/String 使用 UTF-16 編碼儲存。import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public final class HexUnicodeUtil {
/** 字串 → 各編碼十六進制 */
public static void strToHexAll(String text) throws UnsupportedEncodingException {
String[] encs = {"UTF-8","UTF-16","UTF-16LE","UTF-16BE",
"UTF-32","UTF-32LE","UTF-32BE"};
for (String enc : encs) {
byte[] bs = text.getBytes(enc);
StringBuilder sb = new StringBuilder();
for (byte b : bs) sb.append(String.format("%02X", b));
System.out.printf("%-12s: %s%n", enc, sb);
}
}
/** 十六進制字串 → 各編碼解碼嘗試 */
public static void hexToStrAll(String hex) throws UnsupportedEncodingException {
byte[] bs = new byte[hex.length() / 2];
for (int i = 0; i < bs.length; i++) {
bs[i] = (byte) Integer.parseInt(hex.substring(i*2, i*2+2), 16);
}
String[] encs = {"UTF-8","UTF-16","UTF-16LE","UTF-16BE",
"UTF-32","UTF-32LE","UTF-32BE"};
for (String enc : encs) {
try {
System.out.printf("%-12s: %s%n", enc, new String(bs, enc));
} catch (Exception e) {
System.out.printf("%-12s: [解碼失敗]%n", enc);
}
}
}
/** 單一編碼轉換:任意來源編碼 → 目標編碼 */
public static String convert(String text, String fromEnc, String toEnc)
throws UnsupportedEncodingException {
return new String(text.getBytes(fromEnc), toEnc);
}
/** 取得系統支援的所有編碼名稱 */
public static void printAllCharsets() {
Charset.availableCharsets().forEach((name, cs) ->
System.out.println(name + " | " + cs.aliases()));
}
}
public class Demo {
public static void main(String[] args) throws Exception {
String sample = "0 產品型號描述";
System.out.println("=== 字串轉各編碼 Hex ===");
HexUnicodeUtil.strToHexAll(sample);
System.out.println("\n=== Hex 反解各編碼 ===");
HexUnicodeUtil.hexToStrAll("30000900A74EC1548B57F753CF63F08F");
// 實際轉換:Big5 → UTF-8
String big5 = new String(sample.getBytes("Big5"), "ISO-8859-1"); // 模擬錯誤讀取
String fixed = HexUnicodeUtil.convert(big5, "ISO-8859-1", "Big5");
System.out.println("\n修正後: " + fixed);
}
}
| 標準名稱 | 別名 | 說明 |
|---|---|---|
| US-ASCII | ASCII, cp367, IBM367 | 7-bit 英文 |
| UTF-8 | UTF8, unicode-1-1-utf-8 | 最通用、無 BOM |
| UTF-16 | UTF_16, unicode, UnicodeBig | 含 BOM 自動判斷序 |
| UTF-16LE | X-UTF-16LE, UnicodeLittleUnmarked | 小端序、無 BOM |
| UTF-16BE | ISO-10646-UCS-2, X-UTF-16BE | 大端序、無 BOM |
| Big5 | Big5-HKSCS, cp950 | 繁體中文常用 |
| GBK | cp936, windows-936 | 簡體中文常用 |
| ISO-8859-1 | latin1, IBM819 | 西歐語言,常被誤用作單位元組透傳 |
new String(bytes, StandardCharsets.UTF_8)、Files.readString(path, StandardCharsets.UTF_8)。jdbc:mysql://...?characterEncoding=UTF-8。text/html; charset=UTF-8。-Dfile.encoding=UTF-8。StandardCharsets.UTF_8 等常數自 Java 7 起提供,嚴禁使用字串 "UTF-8" 硬編碼。java.nio.charset.Charset.defaultCharset() 回傳 UTF-8),減少跨平台不一致。