【鸿蒙5/6适配】TextDecoder.decodeWithStream接口将要废弃如何适配

32 阅读2分钟

在研发过程中,网络通信、文件操作等场景通常需要使用数据流的方式进行数据处理。decodeWithStream方法为此提供了高效的流式解码能力,支持对分块到达的二进制数据进行实时解码。在网络数据流传输、大文件分块读取及分布式设备通信等场景中发挥关键作用,通过逐块解码的方式显著提升处理效率,降低内存消耗,确保数据处理的实时性和系统性能。 

decodeWithStream方法在从API version 9开始支持,从API version 12开始废弃,官方建议使用decodeToString替代。decodeToString方法在API 12开始支持,仅支持HarmonyOS NEXT的App,可以直接升级了。

下面的代码为使用decodeToString方法及decodeToString进行解码的代码示例

// 原内容,俩毛豆 , 是不是不易查看
let uint8Data = new Uint8Array( [228,191,169,230,175,155,232,177,134]);
//  使用decodeWithStream
let decoder: util.TextDecoder = new util.TextDecoder();
const decodeStr = decoder.decodeWithStream(new Uint8Array(uint8Data));
console.info("tran decodeStr = " + decodeStr);  // tran decodeStr = 俩毛豆

// 下面的代码模拟从网络或文件流中分三次接收的数据块,使用decodeToString进行解码。
// 中文"俩毛豆"的UTF-8编码:[228,191,169,230,175,155,232,177,134]
const dataChunks: Uint8Array[] = [
// "俩" 的完整字节 + "毛" 的部分字节 (230)
  new Uint8Array([228, 191, 169, 230]),
  // "毛" 的剩余字节 (175 155) + "豆" 的部分字节 (232)
  new Uint8Array([175, 155, 232]),
  // "豆" 的剩余字节 (177 134)
  new Uint8Array([177, 134])
];

// 创建解码器配置
let textDecoderOptions: util.TextDecoderOptions = {
  fatal: false,     // 遇到无效字节不抛出异常
  ignoreBOM: true   // 忽略字节顺序标记
};

// 创建解码操作配置 - 使用流模式
let decodeToStringOptions: util.DecodeToStringOptions = {
  stream: true      // 启用流式处理
};

// 创建UTF-8解码器实例
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let finalResult = '';
console.log("开始流式解码...");


// 模拟分三次接收并处理数据
for (let i = 0; i < dataChunks.length; i++) {
  console.log(`处理第${i + 1}个数据块,字节数: ${dataChunks[i].length}`);
  console.log(`数据块${i + 1}十六进制: [${Array.from(dataChunks[i]).map(b => b.toString(16)).join(', ')}]`);

  // 解码当前数据块
  let partialResult = textDecoder.decodeToString(
    dataChunks[i] as Uint8Array,
    decodeToStringOptions
  );

  console.log(`第${i + 1}次解码结果: "${partialResult}"`);
  console.log("---");

  // 累积结果
  if (partialResult) {
    finalResult += partialResult;
  }
}

// 处理完成后,需要调用一次非流式解码以确保所有缓存数据被处理
let flushOptions: util.DecodeToStringOptions = {
  stream: false  // 关闭流模式,刷新缓冲区
};

// 传入空数据来刷新解码器
let flushResult = textDecoder.decodeToString(
  new Uint8Array(0) as Uint8Array,
  flushOptions
);
if (flushResult) {
  console.log(`刷新缓冲区得到: "${flushResult}"`);
  finalResult += flushResult;
}
console.log(`最终解码结果: "${finalResult}"`); // 输出: "俩毛豆"

执行结果日志如下:

cke_6230.png