首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2EE

J2ME 讀取 Unicode 與 UTF-8 編碼文字檔案

     編輯:J2EE

前言

J2ME 應用常需讀取本地化文字資源。MIDP 未提供直接的字元流讀取器,需自行處理位元組轉換。本文提供讀取 Unicode (UTF-16BE) 與 UTF-8 編碼檔案的實用工具方法。

一、讀取 Unicode (UTF-16BE) 檔案

Unicode 文字檔通常以 0xFEFF (BOM) 開頭,佔 2 位元組,讀取時需跳過。每個字元佔 2 位元組,高位在前(Big Endian)。

/**
 * 讀取 Unicode (UTF-16BE) 編碼文字檔
 * @param resource 檔案路徑 (相對 classpath)
 * @return 解碼後字串,失敗回傳 null
 */
public static String readUnicode(String resource) {
    byte[] buffer = new byte[1024];
    InputStream is = null;
    try {
        is = MyClass.class.getResourceAsStream(resource);
        if (is == null) return null;
        is.skip(2); // 跳過 BOM
        int len = is.read(buffer);
        is.close();

        StringBuilder sb = new StringBuilder(len / 2);
        for (int i = 0; i < len; i += 2) {
            int low = buffer[i] & 0xFF;
            int high = buffer[i + 1] & 0xFF;
            char c = (char) ((high << 8) | low);
            sb.append(c);
        }
        return sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) try { is.close(); } catch (IOException ignored) {}
    }
}

二、讀取 UTF-8 檔案

J2ME String 建構子支援指定編碼,直接將位元組陣列轉換即可。

/**
 * 讀取 UTF-8 編碼文字檔
 * @param resource 檔案路徑 (相對 classpath)
 * @return 解碼後字串,失敗回傳 null
 */
public static String readUTF8(String resource) {
    byte[] buffer = new byte[1024];
    InputStream is = null;
    try {
        is = MyClass.class.getResourceAsStream(resource);
        if (is == null) return null;
        int len = is.read(buffer);
        is.close();
        return new String(buffer, 0, len, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) try { is.close(); } catch (IOException ignored) {}
    }
}

注意事項

  • 緩衝區大小 (1024) 需大於檔案實際大小,否則會截斷。實務上可先取得檔案長度再分配,或分段讀取。
  • getResourceAsStream 路徑以 / 開頭表示絕對路徑 (從 JAR 根目錄),不以 / 開頭則相對類別套件。
  • Unicode 讀取假設為 Big Endian (UTF-16BE);若為 Little Endian 需調整高低位組合順序。
  • 例外處理建議記錄日誌而非直接列印堆疊,避免影響效能。

妥善處理編碼讀取,是 J2ME 國際化應用的基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved