天天看点

【OpenHarmony应用开发】处理资源内容文字中文乱码util工具函数示例实现

util工具函数

util工具函数提供了nodejs同样的编解码能力

https://docs.openharmony.cn/pages/v3.1/zh-cn/application-dev/reference/apis/js-apis-util.md/

该模块主要提供常用的工具函数,实现字符串编解码(TextEncoder,TextDecoder)、有理数运算(RationalNumber)、缓冲区管理(LruBuffer)、范围判断(Scope)、Base64编解码(Base64)、内置对象类型检查(Types)等功能。

示例

var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true});
var retStr = textDecoder.decode( result , {stream: false});
           

实现

使用fromCharCode

const content = String.fromCharCode.apply(null, new Uint8Array(buf));
           

使用TextDecoder

实现代码

import ResMgr from '@ohos.resourceManager';
import util from '@ohos.util';
import ability_featureAbility from '@ohos.ability.featureAbility';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  async getResourceFile(resource: Resource): Promise<Uint8Array> {
    let resMgr, result
    try {
      // 获取包名
      let bundleName = await ability_featureAbility.getContext().getBundleName()
      console.log('[TEST]' + bundleName)

      // 获取资源
      resMgr = await ResMgr.getResourceManager(bundleName);
      result = await resMgr.getMedia(resource.id)
    } catch (e) {
      console.log('[TEST]' + e)
    }

    return result
  }

  // utf-8
  Uint8Array2String(buf: Uint8Array): string {
    let textDecoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
    let content = textDecoder.decode(buf, { stream: false })
    return content
  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(async () => {
            try {
              let result = await this.getResourceFile($r('app.media.data'))
              let content = this.Uint8Array2String(result)
              console.log('[TEST][TEST]' + content)
              this.message = content
            } catch (e) {
              console.log('[TEST][TEST]' + e)
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
           

继续阅读