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

如此之白
发布于 2022-9-7 12:02
浏览
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';

示例

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

实现

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

使用fromCharCode

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

【如此之白】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
收藏 1
回复
举报
回复
    相关推荐