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

J2ME 常用字串、日期與編碼轉換工具類庫

     編輯:J2ME

前言

J2ME 核心類庫精簡,缺乏 String.split()、StringBuilder、完整 DateFormat、字符集轉換等常用工具。本文整理三大實用工具類:**字串分割/網絡解碼**、**基礎類型位元組序列化**、**日期時間格式化**,代碼可直接落地專案。

1. StringUtil:字串分割與網絡數據解碼

public class StringUtil {
    /**
     * 分割字串 (替代 String.split,支援單字元/多字元分隔符)
     * @param src 源字串
     * @param delim 分隔符
     * @return 子字串陣列 (不含空尾項)
     */
    public static String[] split(String src, String delim) {
        if (src == null) return null;
        Vector v = new Vector();
        int idx;
        while ((idx = src.indexOf(delim)) != -1) {
            String token = src.substring(0, idx);
            if (token.length() > 0) v.addElement(token);
            src = src.substring(idx + delim.length());
        }
        if (src.length() > 0) v.addElement(src);
        String[] arr = new String[v.size()];
        v.copyInto(arr);
        return arr;
    }

    /**
     * 位元組陣列 → UTF-8 字串 (網絡接收常用)
     * @param bytes 完整位元組陣列
     * @param start 有效資料起始索引
     * @return 解碼字串
     */
    public static String bytesToUtf8(byte[] bytes, int start) {
        byte[] data = new byte[bytes.length - start];
        System.arraycopy(bytes, start, data, 0, data.length);
        try {
            return new String(data, "UTF-8"); // 需 MIDP 2.0
        } catch (UnsupportedEncodingException e) {
            return new String(data); // 退回平台預設
        }
    }
}

2. FormatTransfer:基礎類型 ↔ 位元組陣列 (網絡協議序列化)

採用 **Big Endian (網絡序)**,與 Java DataOutputStream 一致。

public class FormatTransfer {
    // int (4 bytes)
    public static int readInt(byte[] buf, int off) {
        return ((buf[off]   & 0xFF) << 24) |
               ((buf[off+1] & 0xFF) << 16) |
               ((buf[off+2] & 0xFF) << 8)  |
               (buf[off+3] & 0xFF);
    }
    public static void writeInt(byte[] buf, int off, int val) {
        buf[off]   = (byte)(val >> 24);
        buf[off+1] = (byte)(val >> 16);
        buf[off+2] = (byte)(val >> 8);
        buf[off+3] = (byte)val;
    }

    // short (2 bytes)
    public static int readShort(byte[] buf, int off) {
        return ((buf[off] & 0xFF) << 8) | (buf[off+1] & 0xFF);
    }
    public static void writeShort(byte[] buf, int off, short val) {
        buf[off]   = (byte)(val >> 8);
        buf[off+1] = (byte)val;
    }

    // long (8 bytes) - 視需要實現
    // float/double - 需 IEEE 754 轉換 (參考 intBitsToFloat)

    // 陣列追加複製
    public static void append(byte[] dest, int destOff, byte[] src) {
        System.arraycopy(src, 0, dest, destOff, src.length);
    }
}

使用範例:構建協議封包

ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(playerId);
dos.writeShort(itemId);
dos.writeUTF(itemName); // 含長度前綴
byte[] packet = bos.toByteArray();
// 發送...

3. DateTime:日期時間格式化與運算

封裝 Calendar,提供常用格式化字串與相對時間計算。

public final class DateTime {
    private static final String[] WEEK_EN = {"SUN","MON","TUE","WED","THU","FRI","SAT"};
    private static final String[] WEEK_ZH = {"周日","周一","周二","周三","周四","周五","周六"};

    public final int year, month, day, hour, minute, second, millis;
    public final int weekday; // 1~7 (Calendar.SUNDAY=1)

    private DateTime(Calendar c) {
        this.year = c.get(Calendar.YEAR);
        this.month = c.get(Calendar.MONTH) + 1; // 1~12
        this.day = c.get(Calendar.DAY_OF_MONTH);
        this.weekday = c.get(Calendar.DAY_OF_WEEK);
        this.hour = c.get(Calendar.HOUR_OF_DAY);
        this.minute = c.get(Calendar.MINUTE);
        this.second = c.get(Calendar.SECOND);
        this.millis = c.get(Calendar.MILLISECOND);
    }

    public static DateTime now() { return new DateTime(Calendar.getInstance()); }
    public static DateTime fromMillis(long ms) { 
        Calendar c = Calendar.getInstance(); c.setTimeInMillis(ms); 
        return new DateTime(c); 
    }

    // 格式化:2024-05-15 [周三]
    public String toDateString() {
        return year + "-" + pad(month) + "-" + pad(day) + " [" + WEEK_ZH[weekday-1] + "]";
    }
    // 格式化:14:30:05
    public String toTimeString() {
        return pad(hour) + ":" + pad(minute) + ":" + pad(second);
    }
    public String toString() { return toDateString() + " " + toTimeString(); }

    private static String pad(int v) { return (v < 10 ? "0" : "") + v; }

    // 相對時間:N 天前
    public static String daysAgo(int days) {
        return fromMillis(System.currentTimeMillis() - days * 86400000L).toDateString();
    }

    // 轉回 Date
    public Date toDate() {
        Calendar c = Calendar.getInstance();
        c.set(year, month-1, day, hour, minute, second);
        c.set(Calendar.MILLISECOND, millis);
        return c.getTime();
    }
}

編碼轉換補充:ISO-8859-1 ↔ UTF-8 (伺服器端常見)

public class EncodingBridge {
    // 客戶端發送 ISO-8859-1 位元組流,伺服器轉 UTF-8
    public static String isoToUtf8(String isoStr) {
        try {
            return new String(isoStr.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) { return isoStr; }
    }
    // 伺服器 UTF-8 字串 → 客戶端 ISO-8859-1 位元組流
    public static byte[] utf8ToIsoBytes(String utf8Str) {
        try {
            return utf8Str.getBytes("ISO-8859-1");
        } catch (UnsupportedEncodingException e) { return utf8Str.getBytes(); }
    }
}

總結與建議

  • StringUtil.split 替代缺失的 String.split(),注意 Vector 效能,高頻調用可改用 String[] 預分配
  • FormatTransfer 統一網絡位元組序,避免手工移位錯誤
  • DateTime 封裝 Calendar 細節,提供業務級格式化,避免分散 Calendar.get() 呼叫
  • 編碼轉換 僅在 MIDP 2.0/CLDC 1.1 可用,MIDP 1.0 請改用 Unicode 轉義或定點數傳輸
  • 將上述類置於 com.mygame.util 套件,建構腳本自動打包,全專案統一引用
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved