鸿蒙Arkts-子模块访问自己的rawfile下文件

1:调用createModuleContext(context: Context, moduleName: string)方法,获取本应用中其他Module的Context。获取到其他Module的Context之后,即可获取到相应Module的资源信息。

2:调用 getRawFileContent(path: string, callback: _AsyncCallback): void 获取resources/rawfile目录下对应的rawfile文件内容

例如,访问guidelines模块下自己的rawfile目录。

let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
const moduleContext = await application.createModuleContext(context,'guidelines')
// 示例:读取 rawfile 下的 test.txt 文件
if (this.item.title) {
  const rawfilePath = 'text/' + this.item.title + '.txt';
  Logger.debug(`目录:${rawfilePath}`)
  moduleContext.resourceManager.getRawFileContent(rawfilePath)
    .then((value: Uint8Array) => {
      // 成功回调:value 为文件内容的字节数组
      const textDecoder = util.TextDecoder.create('utf-8')
      this.txtContent = textDecoder.decodeToString(value);
    })
    .catch((error: Error) => {
      // 错误处理
      Logger.error(`Error code: ${error.name}, Message: ${error.message}`);
      // 文章内容文件读取失败埋点
      logEvent({
        event_id: 'article_detail_file_read_fail',
        event_name: '文章详情页内容文件读取失败',
        page: PAGE_NAME,
        page_path: PAGE_PATH,
        ext_params: {'article_title': this.item.title.toString(), 'file_path': rawfilePath.toString(), 'error_msg': error.message.toString()}
      });
    });
}