【如此之白】OH处理资源内容中文乱码 原创

如此之白
发布于 2022-9-7 12:02
6625浏览
1收藏

首先,准备一个data.txt文件,输入一段中文文字。将data.txt放在resource/base/media目录下。

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)等功能。

导入模块

import util from '@ohos.util';
  • 1.

示例

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

实现

在UI渲染的中文必须是utf-8编码

使用fromCharCode

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

【如此之白】OH处理资源内容中文乱码-鸿蒙开发者社区

使用TextDecoder

【如此之白】OH处理资源内容中文乱码-鸿蒙开发者社区

实现代码

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.message)
    }

    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]' + content)
              this.message = content
            } catch (e) {
              console.log('[TEST]' + e)
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
1
收藏 1
回复
举报
1
1


回复
    相关推荐