以下内容对应OpenHarmony 3.1 Release 其他版本可能出现问题,请注意 https://docs.openharmony.cn/pages/v3.1/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md/

import ResMg from '@ohos.resourceManager';

$r方法会返回一个Resource类型。

获取resource/base/element资源信息,例如string.json中某个对应值信息

async getString(resource: Resource): Promise<string>{
	let result:string = ''

	try{
		let resMgr = await ResMgr.getResourceManager('com.ohos.myapplication');
		result = await resMgr.getString(resource.id);
	}catch(e){
		console.log(e.message)
	}

	return result
}

// 使用
let result:string = await getString($r('app.string.entry_desc'))

获取其他类型文件内容,例如txt,只要使用方法最后结果返回Uint8Array的都可以。 resource/base/media/data.txt

按道理应该是放在profile里面的,但是3.1release $r('app.profile.data')编译严重错误,已提交issue。 太好笑了IDE和HarmonyOS一样支持profile文件夹,然后一看OpenHarmony文档根本没这个玩意,但是用app.profile还是可以的,只是返回resource JSON格式出错,一天到晚都在搞笑 https://gitee.com/openharmony/arkui_ace_engine/issues/I5BA9M?from=project-issue

async getProfile(resource: Resource): Promise<Uint8Array>{
	let result: Uint8Array

	try{
		let resMgr = await ResMgr.getResourceManager('com.ohos.myapplication');
		result = await resMgr.getMedia(resource.id);
	}catch(e){
		console.log(e.message)
	}

	return result
}

// 使用
let result:Uint8Array = await getString($r('app.media.data'))

获取resource/rawfile内文件信息,传入的是一个文件相对路径,这个文件相对路径是相对于rawfile文件夹的。 所以resource/rawfile/data.txt,path应该写作./data.txt

async getRawFile(path: string): Promise<Uint8Array>{
	let result: Uint8Array

	try{
		let resMgr = await ResMgr.getResourceManager('com.ohos.myapplication');
		result = await resMgr.getRawFile(path);
	}catch(e){
		console.log(e.message)
	}

	return result
}

// 使用
let result:Uint8Array = await getRawFile('./data.txt')

Uint8Array需要转成string类型才可以使用内容信息,见下篇