You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java ME环境下UTF-16BE转UTF-8实现emoji对应png文件名获取

你之前测试代码没有生效的原因:你测试时使用的\u003c属于ASCII范围内的单字符,其UTF-8编码与自身Unicode值完全一致,来回转换自然看不出差异,换用代理对形式的emoji字符测试即可得到预期结果。

方案一:使用Java ME内置编码转换(推荐)

绝大多数支持CLDC 1.1及以上版本的Java ME环境都原生支持UTF-8编码,直接使用内置方法即可:

try {
    // 提取emoji对应的UTF-16代理对
    char highSurrogate = text.charAt(ii - 1);
    char lowSurrogate = text.charAt(ii);
    // 构造仅包含当前emoji的字符串
    String emoji = new String(new char[]{highSurrogate, lowSurrogate});
    // 转换为UTF-8字节数组
    byte[] utf8Bytes = emoji.getBytes("UTF-8");
    // 拼接十六进制文件名
    StringBuffer fileNameBuf = new StringBuffer();
    for (int i = 0; i < utf8Bytes.length; i++) {
        // 处理字节为无符号值
        int unsignedByte = utf8Bytes[i] & 0xFF;
        // 不足两位补前导0
        if (unsignedByte < 0x10) {
            fileNameBuf.append('0');
        }
        fileNameBuf.append(Integer.toHexString(unsignedByte));
    }
    String fileName = fileNameBuf.append(".png").toString();
    // 此处fileName即为你需要的f09f8cbb.png格式
} catch (UnsupportedEncodingException e) {
    // 若当前环境不支持UTF-8编码, fallback到下面的手动转换方案
}

方案二:手动实现编码转换(兼容极端老旧环境)

如果设备环境确实不支持UTF-8编码,可以手动实现代理对到UTF-8的转换逻辑,无需依赖系统编码支持:

// 提取代理对
char highSurrogate = text.charAt(ii - 1);
char lowSurrogate = text.charAt(ii);
// 转换为完整Unicode码点
int codePoint = ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000;
byte[] utf8Bytes;
// 根据码点范围计算UTF-8字节
if (codePoint <= 0x7F) {
    utf8Bytes = new byte[]{(byte) codePoint};
} else if (codePoint <= 0x7FF) {
    utf8Bytes = new byte[]{
        (byte) (0xC0 | (codePoint >> 6)),
        (byte) (0x80 | (codePoint & 0x3F))
    };
} else if (codePoint <= 0xFFFF) {
    utf8Bytes = new byte[]{
        (byte) (0xE0 | (codePoint >> 12)),
        (byte) (0x80 | ((codePoint >> 6) & 0x3F)),
        (byte) (0x80 | (codePoint & 0x3F))
    };
} else {
    utf8Bytes = new byte[]{
        (byte) (0xF0 | (codePoint >> 18)),
        (byte) (0x80 | ((codePoint >> 12) & 0x3F)),
        (byte) (0x80 | ((codePoint >> 6) & 0x3F)),
        (byte) (0x80 | (codePoint & 0x3F))
    };
}
// 拼接文件名逻辑和方案一一致
StringBuffer fileNameBuf = new StringBuffer();
for (int i = 0; i < utf8Bytes.length; i++) {
    int unsignedByte = utf8Bytes[i] & 0xFF;
    if (unsignedByte < 0x10) {
        fileNameBuf.append('0');
    }
    fileNameBuf.append(Integer.toHexString(unsignedByte));
}
String fileName = fileNameBuf.append(".png").toString();

内容的提问来源于stack exchange,提问作者Computershik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:57:04