天天看點

【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%')
  }
}
           

繼續閱讀